library(tidyverse)
lag_multiple <- function(x, n_vec){
map(n_vec, lag, x = x) %>%
set_names(paste0("lag", n_vec)) %>%
as_tibble()
}
df <- tibble(a = 1:10, b = 11:20, c= 21:30)
df %>%
mutate(across(where(is.numeric), list(lags = ~lag_multiple(.x, 1:3)))) %>%
unnest(col = where(is_tibble), names_sep = "_")
#> # A tibble: 10 x 12
#> a b c a_lags_lag1 a_lags_lag2 a_lags_lag3 b_lags_lag1 b_lags_lag2
#> <int> <int> <int> <int> <int> <int> <int> <int>
#> 1 1 11 21 NA NA NA NA NA
#> 2 2 12 22 1 NA NA 11 NA
#> 3 3 13 23 2 1 NA 12 11
#> 4 4 14 24 3 2 1 13 12
#> 5 5 15 25 4 3 2 14 13
#> 6 6 16 26 5 4 3 15 14
#> 7 7 17 27 6 5 4 16 15
#> 8 8 18 28 7 6 5 17 16
#> 9 9 19 29 8 7 6 18 17
#> 10 10 20 30 9 8 7 19 18
#> # ... with 4 more variables: b_lags_lag3 <int>, c_lags_lag1 <int>,
#> # c_lags_lag2 <int>, c_lags_lag3 <int>
Created on 2022-12-06 by the reprex package (v2.0.1)