r - Sort a data.frame by multiple columns whose names are contained in a single object? -
i want sort data.frame
multiple columns, ideally using base r without external packages (though if necessary, it). having read how sort dataframe column(s)?, know can accomplish order()
function long either:
- know explicit names of each of columns.
- have separate object representing each individual column sort.
but if have 1 vector containing multiple column names, of length that's unknown in advance?
say vector called sortnames
.
data[order(data[, sortnames]), ]
won't work, because order()
treats single sorting argument.
data[order(data[, sortnames[1]], data[, sortnames[2]], ...), ]
work if , if specify exact correct number of sortname values, won't know in advance.
things i've looked @ not been totally happy with:
eval(parse(text=paste("data[with(data, order(", paste(sortnames, collapse=","), ")), ]")))
. maybe fine, i've seen plenty of hate usingeval()
, asking alternatives seemed worthwhile.- i may able use
deducer
librarysortdata()
, said, i'd rather avoid using external packages.
if i'm being stubborn not using external packages, let me know. i'll on it. ideas appreciated in advance!
you can use do.call
:
data<-data.frame(a=rnorm(10),b=rnorm(10)) data<-data.frame(a=rnorm(10),b=rnorm(10),c=rnorm(10)) sortnames <- c("a", "b") data[do.call("order", data[sortnames]), ]
this trick useful when want pass multiple arguments function , these arguments in convenient named list.
Comments
Post a Comment