Skip to content

Instantly share code, notes, and snippets.

@brshallo
Last active December 6, 2022 18:04
Show Gist options
  • Save brshallo/8ef983b6e80799dfd978dcce721984d2 to your computer and use it in GitHub Desktop.
Save brshallo/8ef983b6e80799dfd978dcce721984d2 to your computer and use it in GitHub Desktop.
is a riff on https://gist.github.com/brshallo/cadaa40cef6387e28924b6c3756627c9 but allows for use across multiple columns. Could make minor tweak to allow arbitrary function inputs, could also just use dplyover.
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)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment