DaniCee
DaniCee

Reputation: 3207

R: how to order a data frame according to a column AND to a external variable in one command

I want to order a data frame first according to one column in an ascending manner, and to a second column specified by the levels in an external variable.

Given the following MWE:

mylevels <- c("domain", "kingdom", "phylum", "class", "order", "family", "genus", "species")
mydf <- data.frame(ID=rep(c("A","B","C"), each=8), LEVEL=rep(mylevels, 3), VALUE=1:24)
mydf2 <- mydf[sample(nrow(mydf)),]

I want to order mydf2 to obtain the original order in mydf, according to ID ascendantly, and to LEVEL as specified in mylevels, in one command. Is it possible?

(note mydf is kept for demonstration purposes, in my real life case I start from mydf2)

Thanks!

Upvotes: 1

Views: 149

Answers (1)

Marius
Marius

Reputation: 60160

Set factor levels on LEVEL with the correct order, then sort by ID and LEVEL:

mydf2$LEVEL = factor(mydf2$LEVEL, levels = mylevels)
mydf2 = mydf2[order(mydf2$ID, mydf2$LEVEL), ]

Output:

> head(mydf2)
  ID   LEVEL VALUE
1  A  domain     1
2  A kingdom     2
3  A  phylum     3
4  A   class     4
5  A   order     5
6  A  family     6

Upvotes: 1

Related Questions