1

I am looking for an elegant way to assign each row the number of times a certain value of a column has been occuring, example:

df1
Ch1    Year      
X1      2010
X1      2011
X1      2012
X2      2011
X2      2013
...

I want to add a row like this

df1
Ch1    Year      Count
X1      2010      1
X1      2011      2
X1      2012      3
X2      2011      1
X2      2013      2
...

now I know I can create a loop or work with unite/seperate. Is there an easier way to do this?

Thank you

antonina
  • 109
  • 8

1 Answers1

1

One option is group_by sequence

library(dplyr)
df1 %>%
   group_by(Ch1) %>%
   mutate(Count = row_number())

In base R, it can also be done with sequence

df1$Count <- sequence(table(df1$Ch1))
akrun
  • 874,273
  • 37
  • 540
  • 662