I am working on an automation project in R. I want to order an input dataset (i.e. dataframe) by row values. No hardcoded values are allowed, since it's automated code. Reproducible example below:
data("mtcars")
groupBY <- c('cyl','carb')
Normally, I would go on and order with this:
mtcars_ordered <- mtcars[order(mtcars$cyl,mtcars$carb),]
or this:
mtcars_ordered <- mtcars[with(mtcars,order(cyl,carb)),]
but here I am in the 'automated world', no hardcoded values. Thus, I am looking for something like this:
mtcars_ordered_auto <- mtcars[with(mtcars,order(groupBY)),]
order()
accepts vectors, that is subsets of the data frame, but I can't find a way to do it with R base only.
PS Eventually, I succeeded using fn$sqldf as suggested here, by writing:
groupBY_str <- paste(groupBY,collapse=',')
mtcars_ordered_sql <- fn$sqldf('select * from mtcars order by $groupBY_str').
Nonetheless, I am curious how to solve it with base R.