-2

I have following data set

        id      year
2      20332           2005
3       6383           2005
14     20332           2006
15      6806           2006
16     23100           2006

I would like to have an additional column, which counts the number of years the id variable is already available:

        id      year        Counter
2      20332           2005     1
3       6383           2005     1
14     20332           2006     2
15      6806           2006     1
16     23100           2006     1

The dataset is currently not sorted according to the year. I thought about mutate rather than a function.

Any ideas? Thanks!

zx8754
  • 46,390
  • 10
  • 104
  • 180
Nils
  • 129
  • 1
  • 9
  • 1
    Try `df1$Counter – akrun Jan 25 '17 at 15:52
  • 1
    Possible duplicate of [Add column with order counts](http://stackoverflow.com/questions/32470413/add-column-with-order-counts) Or [R: assign incremental numbers to rows containing a same label](http://stackoverflow.com/questions/21663752/r-assign-incremental-numbers-to-rows-containing-a-same-label) – Ronak Shah Jan 25 '17 at 15:55

1 Answers1

1

We can use ave from base R

df1$Counter <- with(df1, ave(id, id, FUN = seq_along))
akrun
  • 789,025
  • 32
  • 460
  • 575