Reorder data.frame and rewrite rostov names?

I have a data.frame like this:

id<-c("001-020", "001-010", "001-051")
name<-c("Fred", "Sue", "Liam")
df<-data.frame(id, name)

      

I tried:

df[with(df, order(id)), ]
#        id name
# 2 001-010  Sue
# 1 001-020 Fred
# 3 001-051 Liam

      

which orders the data.frame correctly, but does not affect the growth names.

How can I reorder the data in a frame using ascending order of the id field and rewrite the role names in one go?

+3


source to share


4 answers


You may try

 newdf <- df[with(df, order(id)), ]
 row.names(newdf) <- NULL

      

Or it can be done in one step

 newdf <- `row.names<-`(df[with(df,order(id)),], NULL)

      

Setting row.names

to on NULL

will also work when you have an empty data.frame file.

  d1 <- data.frame()
  row.names(d1) <- NULL
  d1
  #data frame with 0 columns and 0 rows

      

If we do the same with 1:nrow

 row.names(d1) <-1:nrow(d1)
 #Error in `row.names<-.data.frame`(`*tmp*`, value = c(1L, 0L)) : 
 #invalid 'row.names' length

      




Or another option data.table

 library(data.table)#v1.9.4+
 setorder(setDT(df), id)[]

      

or

 setDT(df)[order(id)]

      


Or using sqldf

 library(sqldf)
 sqldf('select * from df
        order by id')

      

+7


source


You can simply assign a new one rownames

:

df2 <- df[with(df, order(id)), ]
rownames(df2) <- 1:nrow(df2)

      



And a cleaner solution with magrittr

:

library(magrittr)
df %>% extract(order(df$id), ) %>% set_rownames(1:nrow(df))

      

+4


source


I am surprised by this not in the previous answers. What you are looking for is arrange

from plyr

:

library(plyr)

arrange(df, id)
#       id name
#1 001-010  Sue
#2 001-020 Fred
#3 001-051 Liam

      

+3


source


Since string names are stored as an attribute of an object, it might structure()

be here:

structure(df[order(df$id),],row.names=rownames(df));
##        id name
## 1 001-010  Sue
## 2 001-020 Fred
## 3 001-051 Liam

      

+1


source







All Articles