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?
source to share
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')
source to share
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
source to share