Adrian Adrian -3 years ago 104
R Question

How to order column of data.frame by another variable

mydata <- data.frame(id = c(rep(1, 3), rep(2, 3), rep(3, 3)),
score = c(c(1, 2, 3), c(3, 2, 1), c(1, 3, 2)),
location = c(rep(c("X", "Y", "Z"), 3)))
> mydata
id score location
1 1 1 X
2 1 2 Y
3 1 3 Z
4 2 3 X
5 2 2 Y
6 2 1 Z
7 3 1 X
8 3 3 Y
9 3 2 Z


I would like to sort my data.frame according to
score
from smallest to largest for each
id
.

Simplying ordering by
score
ignores the
id
column.

> mydata[with(mydata, order(score)),]
id score location
1 1 1 X
6 2 1 Z
7 3 1 X
2 1 2 Y
5 2 2 Y
9 3 2 Z
3 1 3 Z
4 2 3 X
8 3 3 Y


Essentially, I want my output to be

id score location
1 1 1 X
2 1 2 Y
3 1 3 Z
4 2 1 Z
5 2 2 Y
6 2 3 X
7 3 1 X
8 3 2 Z
9 3 3 Y

Answer Source

You can use dplyr package:

library(dplyr)
mydata %>% arrange(id,score)

#   id score location 
# 1  1     1        X 
# 2  1     2        Y 
# 3  1     3        Z 
# 4  2     1        Z 
# 5  2     2        Y 
# 6  2     3        X 
# 7  3     1        X 
# 8  3     2        Z 
# 9  3     3        Y
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download