0

I have this table df <- data.table(x = c('a','a','a','a','b','b','b','b'), y = c(4,5,6,3,2,2,6,5)) And want to enumerate elements in groups (x variable).

As a result, I want to get df <- data.table(x = c('a','a','a','a','b','b','b','b'), y = c(4,5,6,3,2,2,6,5), z = c(1,2,3,4,1,2,3,4))

  • 3
    [what did your initial search return?](http://stackoverflow.com/search?q=%5Br%5D+number+by+group) Mine gave me [one](http://stackoverflow.com/questions/19848362/adding-a-counter-column-for-a-set-of-similar-rows-in-r), [two](http://stackoverflow.com/questions/32118727/count-the-number-previous-items-in-by-group-in-r), [three](http://stackoverflow.com/questions/8997638/numbering-by-groups), [four](http://stackoverflow.com/questions/8209015/observation-number-by-group), [five](http://stackoverflow.com/questions/10029235/cumulative-count-in-r), comment too long to post more – rawr Feb 25 '16 at 13:27
  • Not really a dupe of that question if you wanted to know about data.table in particular. Anyways, the correct answer in the next version of data.table will be `df[, z := rowid(x)]` – Frank Feb 26 '16 at 00:31

1 Answers1

6

This should do

df[, z := 1:.N, by = x]
danas.zuokas
  • 4,551
  • 4
  • 29
  • 39