Steve
Steve

Reputation: 5977

Order data frame by two columns in R

I'm trying to reorder the rows of a data frame by two factors. For the first factor i'm happy with the default ordering. For the second factor i'd like to impose my own custom order to the rows. Here's some dummy data:

dat <- data.frame(apple=rep(LETTERS[1:10], 3), 
                  orange=c(rep("agg", 10), rep("org", 10), rep("fut", 10)),
                  pear=rnorm(30, 10), 
                  grape=rnorm(30, 10))

I'd like to order "apple" in a specific way:

appleOrdered <- c("E", "D", "J", "A", "F", "G", "I", "B", "H", "C")

I've tried this:

dat <- dat[with(dat, order(orange, rep(appleOrdered, 3))), ]

But it seems to put "apple" into a random order. Any suggestions? Thanks.

Upvotes: 15

Views: 10477

Answers (2)

joran
joran

Reputation: 173577

Try using a factor with the levels in the desired order and the arrange function from plyr:

dat$apple <- factor(dat$apple,levels=appleOrdered)
arrange(dat,orange,apple)

Upvotes: 12

Charles
Charles

Reputation: 4469

Reordering the factor levels:

dat[with(dat, order(orange, as.integer(factor(apple, appleOrdered)))), ]

Upvotes: 12

Related Questions