user3022875
user3022875

Reputation: 9018

apply function to access previous value of different column

I would like to add a new column that is "numbers lagged" but if the group changes I do not want to pick up the previous group as a lagged numbers. This is shown below using ifelse but how would you do this with apply()?

mydata=data.frame(groups = c("A","A","B","B"), numbers= c(1,2,3,4))
mydata$numbers_lagged = lag(mydata$numbers, k=1)  
mydata$groups_lagged= lag(mydata$groups, k=1) 
mydata$numbers_lagged= ifelse(mydata$groups != mydata$groups_lagged,NA, mydata$numbers_lagged) #if the group does not equal the previous group then set to NA
mydata

Upvotes: 0

Views: 51

Answers (1)

BENY
BENY

Reputation: 323226

Compare with apply I recommend using group_by in dplyr

library(dplyr)
mydata%>%group_by(groups)%>%dplyr::mutate(numbers_lagged=lag(numbers))%>%
   ungroup()%>%
   arrange(groups)%>%
   mutate(groups_lagged=lag(groups))

  groups numbers numbers_lagged groups_lagged
  <fctr>   <dbl>          <dbl>        <fctr>
1      A       1             NA            NA
2      A       2              1             A
3      B       3             NA             A
4      B       4              3             B

Upvotes: 1

Related Questions