-1

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 
zx8754
  • 52,746
  • 12
  • 114
  • 209
Gaurav Bansal
  • 5,221
  • 14
  • 45
  • 91

1 Answers1

0

This does it: df$col3 <- unlist(tapply(df$col2, df$col1, lag))

Gaurav Bansal
  • 5,221
  • 14
  • 45
  • 91
  • 1
    Please have a look at [Can I answer my own question?](http://stackoverflow.com/help/self-answer) and come back and check as answered. – help-info.de Jun 24 '19 at 21:06