Easily Switch Which Columns Ordered By

Viewed 27

R uses the three dot ellipses (...) in the function order(...) to pass the multiple vectors to order by. The function immediately converts the ... to a list with z <- list(...).

Let's say we have:

dat = data.frame(A = c(rep("b", 2), rep("a", 2)),
                 B = letters[1:4],
                 C = letters[4:1])

I would like to be able to easily change which columns I want to use (the variable cols) so I don't need to hard code them, incase I want different ones or their names change. Which would look something like this:

cols = c("A", "B")
dat[order(dat[,cols]), ]

But doing the above is equivalent to doing:

dat[order(c(dat$A, dat$B)), ]

Which obviously doesn't work, because it combines the columns into a single vector, so the list created by order() only has the one element, not two.

Is there a way to dynamically create the ... that is passed to functions? Or some other way to achieve what I'm trying to do?

0 Answers
Related