Monday, November 01, 2010

One R Tip A Day: Sorting/ordering a data.frame according specific columns

One R Tip A Day: Sorting/ordering a data.frame according specific columns:

x = rnorm(20)
y = sample(rep(1:2, each = 10))
z = sample(rep(1:4, 5))

data.df <- data.frame(values = x, labels.1 = y, labels.2 = z)
print(data.df)

# data ordered according to 'labels.1' column
# and then 'labels.2' column
nams <- c('labels.1', 'labels.2')
data.df.sorted = data.df[do.call(order, data.df[nams]), ]
print(data.df.sorted)

===================== OR ====================

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))
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

R> 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


- Sent using Google Toolbar"

No comments:

Post a Comment