Kharoof
Kharoof

Reputation: 597

How to sort a dataframe

I want to pass a character vector to a dataframe to sort it. How Can I do this? I have tried the following

headings.tosort <- c("mpg", "hp")
headings <- intersect(headings.tosort, names(mtcars))

mtcars[with(mtcars,order(headings)),]
mtcars[with(mtcars,order(mpg,hp)),]

I want to be able to create a vector with a list of headings to sort and then call it in a dataframe. The first expression does not work but the second one does so how do I get this to work?

Upvotes: 3

Views: 172

Answers (1)

sus_mlm
sus_mlm

Reputation: 1154

I maybe misunderstood your question, but I would do like that:

mtcars[do.call(order, mtcars[, headings]), ]

Upvotes: 4

Related Questions