[R] computing ranks in subgroups

Prof Brian D Ripley ripley at stats.ox.ac.uk
Mon May 29 09:17:44 CEST 2000


On Mon, 29 May 2000, RINNER Heinrich wrote:

> Dear R-users!
> 
> I am using R 1.0.0 and Windows NT 4.0. I want to compute ranks for the
> values of a variable, in several subgroups of a data.frame.
> Currently I use:
> > #example:
> > x <- data.frame(group=c("A","A","B","A","B","B","A"),
> val=c(10,3,9,3,5,1,7))
> > x
>   group val
> 1     A  10
> 2     A   3
> 3     B   9
> 4     A   3
> 5     B   5
> 6     B   1
> 7     A   7
> > x.new<-x[order(x$group),  ]
> > x.new$valgroupranks <- unlist(tapply(x.new$val, x.new$group, rank))
> > x.new
>   group val valgroupranks
> 1     A  10           4.0
> 2     A   3           1.5
> 4     A   3           1.5
> 7     A   7           3.0
> 3     B   9           3.0
> 5     B   5           2.0
> 6     B   1           1.0
> > 
> This seems to work, but I wonder if there is a more "natural" (simple?) way
> to do that?

Look at by():

> by(x[2], x$group, rank)
x$group: A
[1] 4.0 1.5 1.5 3.0
------------------------------------------------------------ 
x$group: B
[1] 3 2 1

> c(by(x[2], x$group, rank),  recursive=T)
 A1  A2  A3  A4  B1  B2  B3 
4.0 1.5 1.5 3.0 3.0 2.0 1.0 



-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272860 (secr)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list