Is it possible to use column values as n in a dplyr::lag function?
Reproducible example:
DF <- data.frame(
V = runif(1000, min=-100, max=100),
nlag = as.integer(runif(1000, min=1, max=10))
) %>%
mutate(Vlag = lag(V, n = nlag))
I get this error:
Error: Evaluation error:
n
must be a nonnegative integer scalar, not integer of length 1000.
Is there any other alternative?
Update:
How do we solve the same problem within groups?
Reproducible example:
DF <- data.frame(
V = runif(1000, min=-100, max=100),
nlag = as.integer(runif(1000, min=1, max=10)),
type = sample(1:4, replace=TRUE)
) %>%
group_by(type) %>%
mutate(Vlag = lag(V, n = nlag))