Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save alejandrohagan/77b3ffe7fa772118ec2000ef1589f6db to your computer and use it in GitHub Desktop.
Save alejandrohagan/77b3ffe7fa772118ec2000ef1589f6db to your computer and use it in GitHub Desktop.
recursive lag function in tidyverse
library(tidyverse)
# sample data
data <- tibble(
headcount=c(100,NA,NA)
,attrition=rep(.03,3)
,hiring=c(10,20,30)
)
# solution
data |>
mutate(
headcount=accumulate2(.x=attrition[-1],.y=hiring[-1],.f=\(prev,.x,.y){
out <- prev*(1-.x)+.y
}
,.init=first(headcount)
)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment