mcpeterson
mcpeterson

Reputation: 5134

Sort a dataframe in R by a dynamic set of columns named in another data frame

I have some data:

dd <- data.frame(cbind(c("A", "A", "B"), c("F", "E", "D"), c(1, 2, 3)))
names(dd) <- c("colA", "colB", "colC")

and I have a lookup frame lk

lk <- data.frame(rbind(c("colA", "colC"), c("colB", "colC")))
names(lk) <- c("srt_col", "srt_metric")

And what I want to do, is sort the data, by the columns named in the lookup frame.

Something like:

dd[ order(lk[, 1]), ]

which should give an output of

output data (roughly, you get the idea I hope)
A  E  2
A  F  1
B  D  3

but I can't seem to get the right syntax, and I feel like I'm missing something obvious here. Can anyone help here?

Upvotes: 1

Views: 995

Answers (1)

Hong Ooi
Hong Ooi

Reputation: 57697

Here's a stab at it.

dd[do.call(order, dd[as.character(lk[, 1])]), ]

The as.character is to avoid any possible factor shenanigans.

Upvotes: 6

Related Questions