0

I have a dataframe that has a certain column, table$NAME, consisted of several thousand rows, and looks like this:

   NAME    
1  namea
2  nameb
3  nameb
4  nameb
5  namec
6  named
7  named
8  named
9  namee
10 namee
.
.
.

What I want is to add a sequence in table$Counter that starts from 1 every time that NAME changes. The output should be something like:

   NAME   Counter
1  namea      1
2  nameb      1
3  nameb      2
4  nameb      3
5  namec      1
6  named      1
7  named      2
8  named      3
9  namee      1
10 namee      2
.
.
.
Leonardo
  • 2,439
  • 33
  • 17
  • 31
Stathis G.
  • 145
  • 2
  • 11

1 Answers1

0

One option in base R is to get the table of 'Name' and wrap it with sequence (assuming that the 'Name' column is already ordered)

df1$Counter <- sequence(table(df1$Name))

Or with ave

with(df1, ave(seq_along(Name), Name, FUN = seq_along))

Or with dplyr

library(dplyr)
df1 %>%
   group_by(Name) %>%
   mutate(Counter = row_number())
akrun
  • 874,273
  • 37
  • 540
  • 662