[R] enumeration variable by groups

jim holtman jholtman at gmail.com
Wed Nov 14 19:30:46 CET 2007


Here is a way to do it:

> x <- scan(textConnection("1 48  1 45  2 50  2 42  1 41  2 51  1 52  1 43  2 52"), what=0L)
Read 18 items
> x <- matrix(x, ncol=2, byrow=TRUE)
> colnames(x) <- c('gender', 'score')
> x
      gender score
 [1,]      1    48
 [2,]      1    45
 [3,]      2    50
 [4,]      2    42
 [5,]      1    41
 [6,]      2    51
 [7,]      1    52
 [8,]      1    43
 [9,]      2    52
> # split out categories
> y <- split(seq_len(nrow(x)), x[,1])
> # combine into new matrix
> x.new <- do.call('rbind', lapply(y, function(.row) cbind(x[.row,], index=seq_along(.row))))
> x.new
      gender score index
 [1,]      1    48     1
 [2,]      1    45     2
 [3,]      1    41     3
 [4,]      1    52     4
 [5,]      1    43     5
 [6,]      2    50     1
 [7,]      2    42     2
 [8,]      2    51     3
 [9,]      2    52     4
>
>



On Nov 14, 2007 12:58 PM, lamack lamack <lamac_k at hotmail.com> wrote:
>
>
>
>
>
> Dear all, How can I create an enumeration variable by groups?
>
> I have:
> gender score  1 48  1 45  2 50  2 42  1 41  2 51  1 52  1 43  2 52
>
> and Y would like to get:
>
>        gender    score    index
>         1        48       1
>         1        45       2
>         1        41       3
>         1        52       4
>         1        43       5
>         2        50       1
>         2        42       2
>         2        51       3
>         2        52       4
> best regards
> _________________________________________________________________
>
> [[replacing trailing spam]]
>
>        [[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.
>



-- 
Jim Holtman
Cincinnati, OH
+1 513 646 9390

What is the problem you are trying to solve?



More information about the R-help mailing list