[R] Find the three best values in every row

Gabor Grothendieck ggrothendieck at gmail.com
Fri May 7 18:31:08 CEST 2010


Using d from the post of S Ellison, try

val <- apply(d, 1, function(x) head(sort(x, decreasing = TRUE), 3))
co <- apply(d, 1, function(x) head(names(d)[order(x, decreasing = TRUE)], 3))
data.frame(values = c(val), countries = c(co), row = c(col(val)))

The first line gives a matrix of the three highest values.
The second line gives a matrix of the three highest countries.
The third line produces a data frame from the two plus the row number from d.


On Fri, May 7, 2010 at 10:44 AM, S Ellison <S.Ellison at lgc.co.uk> wrote:
> Hmm...
>
>  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)
>                )
>
> #Get three top from each row
> t(apply(d,1,function(x,n) x[which(rank(x)> length(x)-n)], n=3))
>
> #Get them with names
> get.n<- function(x, names, n)   {
>        rmin<-
>        rv<-x[w<-which(rank(x)> length(x)-n)]
>        names(rv)<-names[w]
>        return(as.data.frame(rv))
> }
>
> apply(d,1,get.n, n=3, names=names(d))
>
>
>
>>>> Alfred Schulze <Alfred-Schulze at web.de> 05/07/10 2:43 PM >>>
>
>   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
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
>
> *******************************************************************
> This email and any attachments are confidential. Any use...{{dropped:8}}
>
> ______________________________________________
> 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