Search code examples
rdataframelag

Fill in N lags based on a variable in R data frame


I have two columns in my data frame, value and num_leads. I'd like to create a third column that stores the value's value from n rows below - where n is whatever number is stored in num_leads. Here's an example:

df1 <- data.frame(value = c(1:5),
                  num_leads = c(2, 3, 1, 1, 0))

Desired output:

  value num_leads  result
1     1         2       3
2     2         3       5
3     3         1       4
4     4         1       5
5     5         0       5

I have tried using the lead function in dplyr but unfortunately it seems all the leads must have the same number.


Solution

  • using indexing

    with(df1, value[seq_along(value) + num_leads])
    

    where seq_along(value) gives the row number, and by adding to num_leads you can pull out the right value