rtimercountercumulative-frequency

R counter, counting frequency in a table


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!


Solution

  • We can use ave from base R

    df1$Counter <- with(df1, ave(id, id, FUN = seq_along))