# [R] Find the three best values in every row

Patrick Hausmann patrick.hausmann at uni-bremen.de
Fri May 7 18:23:57 CEST 2010

```Hello Alfred,

I found the solution from S. Ellison
(https://stat.ethz.ch/pipermail/r-help/2010-May/238158.html) really
inspiring.
Here I am using tail and the library 'plyr':

set.seed(17*11)
d<-data.frame(africa=sample(50, 10),
europe= sample(50, 10),
n.america= sample(50, 10),
s.america= sample(50, 10),
antarctica= sample((1:50)/20, 10)
)

# using tail
t(apply(d, 1, function(x, n) tail(sort(x), n), n=3))

lapply(split(d, rownames(d)), function(x, n) sort(x)[n:ncol(x)], n=3)

# with plyr from Hadley Wickham
library(plyr)
ldply(split(d, rownames(d)), function(x, n) sort(x)[n : ncol(x)], n=3)

HTH
Patrick

Am 07.05.2010 15:43, schrieb Alfred Schulze:
>
>     Hello,
>
>     i have a dataframe with the GDP for different Country (in the columns) and
>     Years (in the rows).
>
>     Now i want for every year the best three values, if possible with name of
>     the countries (columnnames).
>
>     For the best it's no problem but for the other two values.
>
>     Thanks,
>
>     Alfred
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help