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

From: Dennis Murphy <djmuser_at_gmail.com>
Date: Fri, 27 May 2011 14:14:19 -0700

Hi:

Another angle. Calling your example data frame df,

df <- transform(df, Rank = with(df, ave(value, level, FUN = rank))) df[with(df, order(level, value)), ]
  value level Rank

3     2     A    1
1     4     A    2
2     5     A    3
5     9     B    1
4    10     B    2
6    34     B    3
9    34     C    1
7   100     C    2
8   101     C    3

Note: If you try to use rank = blah instead of Rank = blah in transform(), an error will be thrown; another reason not to use the names of functions in the base package as variable names.

Dennis

On Fri, May 27, 2011 at 12:12 PM, xin wei <xinwei_at_stat.psu.edu> 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
>
> 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.
>



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. Received on Fri 27 May 2011 - 21:17:37 GMT

This quarter's messages: by month, or sorted: [ by date ] [ by thread ] [ by subject ] [ by author ]

All messages

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Tue 31 May 2011 - 19:40:10 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive