Created
March 8, 2025 02:34
-
-
Save alejandrohagan/77b3ffe7fa772118ec2000ef1589f6db to your computer and use it in GitHub Desktop.
recursive lag function in tidyverse
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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