How to sort and filter data.frame in R?

User picture User · Mar 16, 2012 · Viewed 15.6k times · Source

I understand how to sort a data frame:

df[order(df$Height),]

and I understand how to filter (or subset) a data frame matching some predicate:

df[df$Weight > 120,]

but how do I sort and filter (as an example, order by Height and filter by Weight)?

Answer

Dirk Eddelbuettel picture Dirk Eddelbuettel · Mar 16, 2012

Either in two steps

 df1 <- df[df$weight > 120, ]
 df2 <- df1[order(df1$height), ]

or if you must in one step -- but it really is not any cleaner.

Data first:

R> set.seed(42)
R> df <- data.frame(weight=rnorm(10, 120, 10), height=rnorm(10, 160, 20))
R> df
   weight height
1   133.7  186.1
2   114.4  205.7
3   123.6  132.2
4   126.3  154.4
5   124.0  157.3
6   118.9  172.7
7   135.1  154.3
8   119.1  106.9
9   140.2  111.2
10  119.4  186.4

And one way of doing it is double-subsetting:

R> subset(df, weight > 120)[order(subset(df, weight > 120)$height),]
  weight height
9  140.2  111.2
3  123.6  132.2
7  135.1  154.3
4  126.3  154.4
5  124.0  157.3
1  133.7  186.1
R> 

I'd go with the two-step.