-1

I am quite new to R and need some help with a task. My dataframe data1 looks something like that:

ID    Action
A1    A
A1    E
A2    B
B1    A
B2    C
B2    D   
B2    A
B3    E

I need to create a new column Sequence, which increments based on the ID and basically tells me, how often an Action was beeing performed on this ID at that time. For a new ID it would start again from 1. It would look something like that:

ID    Action  Sequence
A1    A       1
A1    E       2
A2    B       1
B1    A       1
B2    C       1
B2    D       2
B2    A       3
B3    E       1

I already tried searching for a similar problem, but could just find solutions, where the number of occurencies was counted without incrementing.

It would be great if you could help me

Thanks in advance!

1 Answers1

2

You can use getanID from splitstackshape

library(splitstackshape)
 getanID(df, 'ID')
 #     ID Action .id
 #1: A1      A   1
 #2: A1      E   2
 #3: A2      B   1
 #4: B1      A   1
 #5: B2      C   1
 #6: B2      D   2
 #7: B2      A   3
 #8: B3      E   1

Or ave from base R

transform(df, Sequence=ave(seq_along(ID), ID, FUN=seq_along))
#    ID Action Sequence
#1 A1      A        1
#2 A1      E        2
#3 A2      B        1
#4 B1      A        1
#5 B2      C        1
#6 B2      D        2
#7 B2      A        3
#8 B3      E        1
akrun
  • 874,273
  • 37
  • 540
  • 662