use purrr functions and mutate to create multiple new columns

i have this dataset..

tbl = tibble(date = seq.Date(as_date("2021-07-20"), Sys.Date(), by = "day"), 
              sales=1:8)
tbl
# A tibble: 8 x 2
  date       sales
  <date>     <int>
1 2021-07-20     1
2 2021-07-21     2
3 2021-07-22     3
4 2021-07-23     4
5 2021-07-24     5
6 2021-07-25     6
7 2021-07-26     7
8 2021-07-27     8

..and want to create lag features like so:

# A tibble: 8 x 6
  date       sales sales_lag_1 sales_lag_2 sales_lag_3 sales_lag_4
  <date>     <int>       <int>       <int>       <int>       <int>
1 2021-07-20     1          NA          NA          NA          NA
2 2021-07-21     2           1          NA          NA          NA
3 2021-07-22     3           2           1          NA          NA
4 2021-07-23     4           3           2           1          NA
5 2021-07-24     5           4           3           2           1
6 2021-07-25     6           5           4           3           2
7 2021-07-26     7           6           5           4           3
8 2021-07-27     8           7           6           5           4

But instead of calling dplyr::lag() multiple times like so:

tbl %>% mutate(sales_lag_1 = lag(sales, 1), 
               sales_lag_2 = lag(sales, 2),
               sales_lag_3 = lag(sales, 3), 
               sales_lag_4 = lag(sales, 4))

i am looking for a appropriate code to generate the same output with purrr functions.

Try this

library(tidyverse)
df <- tibble(date = seq.Date(lubridate::as_date("2021-07-20"), Sys.Date(), by = "day"),  sales=1:8)
lags <- map2_dfc(list(df$sales), 1:10, lag) %>% setNames(paste0("sales_lag_", 1:ncol(.))) 
df <- bind_cols(df, lags)
1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.