I have an R data.frame like shown below. I want to create a new column, col3
that will have the previous value of col2
grouped by col1
. How can I do that?
# Set up dataframe
df <- data.frame(
col1=c('a','a','a','b','b','b'),
col2=c('action1', 'action2', 'action3', 'action1', 'action2', 'action3')
)
df
col1 col2
1 a action1
2 a action2
3 a action3
4 b action1
5 b action2
6 b action3
# What I want:
df
col1 col2 col3
1 a action1 NA
2 a action2 action1
3 a action3 action2
4 b action1 NA
5 b action2 action1
6 b action3 action2