0

In the following code snippet, data is ordered by col1 followed by col2, I want to make the order statement generic so that if data has additional columns e.g. col3 the same order statement will work to sort the data by the additional columns in the order they appear (so, order by col1, then col2, then col3). Essentially need to make order statement dynamic

df <- cbind(c("c","a","b"))

df <- cbind(df, c(2,3,1))

df <- as.data.frame(df)

names(df)[1] <- "col1"

names(df)[2] <- "col2"

df[order(df$col1, df$col2),]
divibisan
  • 11,659
  • 11
  • 40
  • 58
Nasir
  • 167
  • 6

1 Answers1

1

This should work:

df[do.call(order, as.list(df)), ]
Ciarán Tobin
  • 7,306
  • 1
  • 29
  • 45
  • Thanks, it worked. With this I was able to get to below df <- cbind(c("c","a","a")) df <- cbind(df, c(2,1,1)) df <- cbind(df, c("n","m","o")) df <- as.data.frame(df) names(df)[1] <- "col1" names(df)[2] <- "col2" names(df)[3] <- "col3" order_by_cols <- 3 df[do.call(order, as.list(df[,c(1:order_by_cols)])), ] – Nasir Aug 18 '15 at 19:04