RE: [R] how to create a variable to rank within subgroups

From: Liaw, Andy <andy_liaw_at_merck.com>
Date: Tue 07 Jun 2005 - 11:21:33 EST


Try something like:

> g <- gl(4, 5)
> x <- sample(20)

> d <- data.frame(g, x)
> d

   g x
1 1 10
2 1 3
3 1 11
4 1 12
5 1 20
6 2 13
7 2 6
8 2 2
9 2 1
10 2 14
11 3 17
12 3 15
13 3 16
14 3 19
15 3 9
16 4 4
17 4 7
18 4 5
19 4 8
20 4 18
> d$xrank <- ave(d$x, d$g, FUN=rank)
> d

   g x xrank

1  1 10     2
2  1  3     1
3  1 11     3
4  1 12     4
5  1 20     5
6  2 13     4
7  2  6     3
8  2  2     2
9  2  1     1
10 2 14     5
11 3 17     4
12 3 15     2
13 3 16     3
14 3 19     5
15 3  9     1
16 4  4     1
17 4  7     3
18 4  5     2
19 4  8     4
20 4 18     5

Andy

> From: Denis Chabot
>
> Hi,
>
> I would like to create a new variable that would be the rank of a
> continuous variable within each level of a grouping variable.
> Say the
> first level of the grouping variable has 5 observations, I'd like
> them ranked from one to five and a new variable would hold the rank
> value (one to five). So forth for each level of the grouping variable.
>
> I'm quite new with R and cannot figure out this one by myself.
>
> Thanks in advance,
>
> Denis Chabot
>
> ______________________________________________
> R-help@stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide!
> http://www.R-project.org/posting-guide.html
>
>
>



R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html Received on Tue Jun 07 11:29:36 2005

This archive was generated by hypermail 2.1.8 : Fri 03 Mar 2006 - 03:32:25 EST