[R] Odp: Select top three values from data frame

Petr PIKAL petr.pikal at precheza.cz
Wed Aug 26 11:38:01 CEST 2009


Hi

r-help-bounces at r-project.org napsal dne 26.08.2009 10:36:22:

> Hi,
> 
> I'm trying to find an easy way to do this.
> 
> I want to select the top three values of a specific column in a subset 
> of rows in a data.frame.  I'll demonstrate.
> 
> A    B    C
> x    2    1
> x    4    1
> x    3    2
> y    1    5
> y    2    6
> y    3    8
> 
> 
> I want the top 3 values of B from the data.frame where A=X and C <2
> 
> I could extract all the rows where C<2, then sort by B, then take the 
> first 3.  But that seems like the wrong way around, and it also will get 

> messy with real data of over 100 columns.

One way is to use subset, order and head

head(subset(your.data[order(your.data$B, decreasing=T),], subset = C<2 & 
A=="x"), 3)

Regards
Petr


> 
> Any suggestions?
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide 
http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.




More information about the R-help mailing list