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

Denis Chabot chabotd at globetrotter.net
Tue Jun 7 12:04:16 CEST 2005


Thank you very much Andy, this is exactly what I was looking for. I  
did not know this function.

Sincerely,

Denis Chabot
Le 06 juin 2005 à 21:21, Liaw, Andy a écrit :

> 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 at 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
>>
>>
>>
>>
>
>
>
> ---------------------------------------------------------------------- 
> --------
> Notice:  This e-mail message, together with any attachments,  
> contains information of Merck & Co., Inc. (One Merck Drive,  
> Whitehouse Station, New Jersey, USA 08889), and/or its affiliates  
> (which may be known outside the United States as Merck Frosst,  
> Merck Sharp & Dohme or MSD and in Japan, as Banyu) that may be  
> confidential, proprietary copyrighted and/or legally privileged. It  
> is intended solely for the use of the individual or entity named on  
> this message.  If you are not the intended recipient, and have  
> received this message in error, please notify us immediately by  
> reply e-mail and then delete it from your system.
> ---------------------------------------------------------------------- 
> --------
>




More information about the R-help mailing list