Maybe this? I used some code from the previous solution from @cactusoxbird .
library(tidyverse)
library(lubridate)
#>
#> Attaching package: 'lubridate'
#> The following objects are masked from 'package:base':
#>
#> date, intersect, setdiff, union
make_lag <- function(df, n_lag) {
# lag the numeric columns of a data frame
df %>%
select_if(is.numeric) %>%
lag(n_lag) %>%
rename_all(str_c, "_lag", n_lag)
}
make_lags <- function(df, lags) {
# bind a data frame with lagged numeric columns. lags is an integer vector of lags, e.g. 1:5
bind_cols(df, map2(list(df), lags, make_lag))
}
# make fake data
clim <-
expand_grid(
neighborhood = factor(seq(1, 10)),
clim_date = seq(from = ymd("2014-01-01"), to = ymd("2014-12-01"), by = "month"),
) %>%
mutate(
precip = rnorm(n = n(), mean = 500, sd = 50),
temp = rnorm(n = n(), mean = 35, sd = 10),
humidity = rnorm(n = n(), mean = 80, sd = 2)
) %>%
# add lags within each neighborhood
group_by(neighborhood) %>% group_split() %>%
map_dfr(make_lags, 1:5)
print(clim)
#> # A tibble: 120 x 20
#> neighborhood clim_date precip temp humidity precip_lag1 temp_lag1
#> <fct> <date> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 1 2014-01-01 525. 42.1 82.6 NA NA
#> 2 1 2014-02-01 445. 36.2 82.7 525. 42.1
#> 3 1 2014-03-01 440. 40.5 80.7 445. 36.2
#> 4 1 2014-04-01 473. 43.3 77.9 440. 40.5
#> 5 1 2014-05-01 540. 29.6 79.6 473. 43.3
#> 6 1 2014-06-01 523. 12.1 78.4 540. 29.6
#> 7 1 2014-07-01 483. 30.7 80.9 523. 12.1
#> 8 1 2014-08-01 538. 30.1 80.7 483. 30.7
#> 9 1 2014-09-01 533. 21.6 81.7 538. 30.1
#> 10 1 2014-10-01 523. 28.8 80.6 533. 21.6
#> # ... with 110 more rows, and 13 more variables: humidity_lag1 <dbl>,
#> # precip_lag2 <dbl>, temp_lag2 <dbl>, humidity_lag2 <dbl>, precip_lag3 <dbl>,
#> # temp_lag3 <dbl>, humidity_lag3 <dbl>, precip_lag4 <dbl>, temp_lag4 <dbl>,
#> # humidity_lag4 <dbl>, precip_lag5 <dbl>, temp_lag5 <dbl>,
#> # humidity_lag5 <dbl>
Created on 2022-01-11 by the reprex package (v2.0.1)