[R] Conditonal Rank

Dennis Murphy djmuser at gmail.com
Fri Apr 29 23:04:30 CEST 2011


Hi:

Does this work?

library(plyr)
ddply(tmp, .(trial, Gender), transform, rankscore = rank(score))
  score trial Gender rankscore
1     1     1      M         1
2     2     1      M         2
3     3     1      F         1
4     4     1      F         2
5     4     2      M         2
6     3     2      M         1
7     2     2      F         2
8     1     2      F         1

Alternatively, you could get the 'wide form' with

aggregate(score ~ trial + Gender, data = tmp, FUN = rank)
  trial Gender score.1 score.2
1     1      M       1       2
2     2      M       2       1
3     1      F       1       2
4     2      F       2       1

HTH,
Dennis


On Fri, Apr 29, 2011 at 12:26 PM, Doran, Harold <HDoran at air.org> wrote:
> Suppose I have data such as
>
> tmp <- data.frame(score = c(1,2,3,4, 4,3,2,1), trial = gl(2,4), Gender = gl(2,2,8, labels=c('M', 'F')))
>
> Now I would like to compute a rank on the variable score conditional on trial and gender. I could do
>
> res <- with(tmp, tapply(score, list(Gender, trial), rank))
> res[,1]
> res[,2]
>
> and then finagle a way to create a new variable in the dataframe tmp that has these ranks associated with the correct rows. But, perhaps there is a better way. Any suggestions?
>
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> 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