Multiple outputs from one line of dplyr::mutate?

Close but not quite. That generates a two-sided formula. chg_d1, chg_d2 etc. are the list element names, not the LHS. But your attempt encouraged me to not be lazy and actually give it a shot. :wink:

library(dplyr, warn.conflicts = FALSE)
library(purrr)

fns_list_gen <- function(n_lags) {
  fns_list <- map(1:n_lags, ~ as.formula(paste0(" ~ .x - lag(.x, ", .x, "L)")))
  set_names(fns_list, nm = paste0("chg_d", 1:n_lags))
}

fns_list <- fns_list_gen(n_lags = 4)

df1 <- tibble::tribble(
  ~day, ~sales,
  1L, 260L,
  2L, 230L,
  3L, 110L,
  4L, 420L,
  5L, 420L,
  6L, 380L,
  7L, 360L,
  8L, 860L,
  9L, 300L,
  10L, 240L
)

mutate(df1, across(.cols = sales, .fns = fns_list, .names = "{col}_{fn}"))
#> # A tibble: 10 x 6
#>      day sales sales_chg_d1 sales_chg_d2 sales_chg_d3 sales_chg_d4
#>    <int> <int>        <int>        <int>        <int>        <int>
#>  1     1   260           NA           NA           NA           NA
#>  2     2   230          -30           NA           NA           NA
#>  3     3   110         -120         -150           NA           NA
#>  4     4   420          310          190          160           NA
#>  5     5   420            0          310          190          160
#>  6     6   380          -40          -40          270          150
#>  7     7   360          -20          -60          -60          250
#>  8     8   860          500          480          440          440
#>  9     9   300         -560          -60          -80         -120
#> 10    10   240          -60         -620         -120         -140

Created on 2020-07-08 by the reprex package (v0.3.0)

2 Likes