[R] sort the values of members and obtain their ranks within groups

Liaw, Andy andy_liaw at merck.com
Tue May 23 04:04:03 CEST 2006


See if this does what you want:
 
> cbind(df, rank=ave(df$member, df$group, FUN=rank))
  group member rank
1     1     30    3
2     1     10    1
3     1     22    2
4     5     21    2
5     5     44    3
6     5     15    1

Andy

  _____  

From: r-help-bounces at stat.math.ethz.ch on behalf of Zhen Zhang
Sent: Mon 5/22/2006 6:40 PM
To: R-help at stat.math.ethz.ch
Subject: [R] sort the values of members and obtain their ranks within groups
[Broadcast]



Dear all, 

I would like to sort the values of "member" for each group, and obtain a 
variable to indicate its rank within the group. 

For example, we have original dataset as follows: 

df <- data.frame(group = c(rep(1, 3), rep(5, 3)), 
 member = c(30, 10, 22, 21, 44, 15)) 

  group member 
1     1     30 
2     1     10 
3     1     22 
4     5     21 
5     5     44 
6     5     15 

After sorting the variable "member", we want the dataset like this: 

  group member order 
1     1     30     3 
2     1     10     1 
3     1     22     2 
4     5     21     2 
5     5     44     3 
6     5     15     1 

I already searched the R helper archives, but failed to find the proper 
answers. 

Could you please kindly give me some suggestions, except using loop because 
of larger sample size?  Thanka a lot. 


Best regards, 

Zhen Zhang 

        [[alternative HTML version deleted]] 

______________________________________________ 
R-help at stat.math.ethz.ch mailing list 
https://stat.ethz.ch/mailman/listinfo/r-help
<https://stat.ethz.ch/mailman/listinfo/r-help>  
PLEASE do read the posting guide!
http://www.R-project.org/posting-guide.html
<http://www.R-project.org/posting-guide.html>



More information about the R-help mailing list