[R] how to add row index based a categorical column

David Winsemius dwinsemius at comcast.net
Fri May 27 22:51:09 CEST 2011


On May 27, 2011, at 3:12 PM, xin wei wrote:

> hello, I have the following data manipulation issue. the following  
> is the
> sample data:
>
> value level
> 4       A
> 5       A
> 2       A
> 10     B
> 9       B
> 34     B
> 100   C
> 34     C
> 101    C.
>
> I hope to get the following result:
> value level  rank
> 2       A       1
> 4       A       2
> 5       A       3
> 9       B       1
> 10      B      2
> 34      B      3
> 34      C      1
> 100    C       2
> 101    C.      3
>

Probably something along these lines:

d2 <- d1[order(d1$value, ]
d2$rank <- ave(d2$value, d2$level, FUN=order)

> as you may see, I need the data sorted and indexed within each level  
> of
> "level". what do I need to do calculate the rank variable?
>
> thanks,
>
> --
> View this message in context: http://r.789695.n4.nabble.com/how-to-add-row-index-based-a-categorical-column-tp3556126p3556126.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> 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.

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list