# Basic example with a vector
dates <- as.Date("2023-01-01") + 0:9
values <- rnorm(10)
lagged_values <- lag_column(values, dates, lag = 1, max_lag = 3)
# Example using a tibble and dplyr::group_by
data <- tibble::tibble(
permno = rep(1:2, each = 10),
date = rep(seq.Date(as.Date('2023-01-01'), by = "month", length.out = 10), 2),
size = runif(20, 100, 200),
bm = runif(20, 0.5, 1.5)
)
data |>
dplyr::group_by(permno) |>
dplyr::mutate(
across(c(size, bm),
\(x) lag_column(x, date, months(3), months(6), drop_na = TRUE))
) |>
dplyr::ungroup()
Run the code above in your browser using DataLab