Reputation: 12102
My question is similar to few other sorting/ordering questions but not the same. The question is basically how to sort/order dataframes or datatables in R when the column to sort by is stored in a variable.
Say I have a data frame
#create data frame
df <- data.frame(a=c(2,2,2,2,1,1,3,3,3,3,4,4),
b=c("c","c","a","a","a","b","b","d","d","d","e","e"),
c=c(123,223,1232,122,1232,345,243,456,5676,34,233,111),
stringsAsFactors=F)
There are numerous ways to order the dataframe. Some of the base approaches are:
#ordering dataframe by column 1
df[with(df,order(df[,1])), ]
#ordering dataframe by column name 'a'
df[with(df,order(df[,"a"])), ]
Similarly, with datatables:
library(data.table)
dt <- as.data.table(df)
dt[order(a)]
But, if my column to order by is stored in a variable var
, how do I use that?
#sort by column 1
var <- 1
#sort by column name "a"
var <- "a"
Taking a step further, how do I sort by multiple columns?
#sort by columns 1 and 2
var1 <- 1
var2 <- 2
Upvotes: 1
Views: 1921
Reputation: 1361
try this
df[order(df[[var]]),]
EDIT thanks to David or this if you have multiple conditions
df[order(df[,var]),]
Upvotes: 1