Likan Zhan

Order a data frame by columns

Likan Zhan · 2017-03-07

Addapted from Dirk Eddelbuettel’s stackoverflow post.

Given a data frame

dd <- data.frame(
      b = factor(c("Hi", "Med", "Hi", "Low"),
      levels = c("Low", "Med", "Hi"), ordered = TRUE),
      x = c("A", "D", "A", "C"), y = c(8, 3, 9, 9),
      z = c(1, 1, 1, 2))
return(dd)
##     b x y z
## 1  Hi A 8 1
## 2 Med D 3 1
## 3  Hi A 9 1
## 4 Low C 9 2

We can use the order() function to sort the data frame

dd[with(dd, order(-z, b)), ]
##     b x y z
## 4 Low C 9 2
## 2 Med D 3 1
## 1  Hi A 8 1
## 3  Hi A 9 1
dd[ order(-dd[,4], dd[,1]), ]
##     b x y z
## 4 Low C 9 2
## 2 Med D 3 1
## 1  Hi A 8 1
## 3  Hi A 9 1