View source: R/add_lagged_columns.R
| add_lagged_columns | R Documentation |
Appends lagged versions of specified columns to a data frame using a join-based approach.
add_lagged_columns(
data,
cols,
lag,
max_lag = lag,
by = NULL,
drop_na = FALSE,
ff_adjustment = FALSE,
data_options = NULL
)
data |
A data frame containing the variables to lag. |
cols |
A character vector specifying the names of the columns to be
lagged. Each column produces a new column suffixed with |
lag |
An integer or a |
max_lag |
An integer or a |
by |
An optional character vector specifying grouping columns
(e.g., a stock identifier). Lagged values are matched within groups.
Defaults to |
drop_na |
A logical value. If |
ff_adjustment |
A logical value. If |
data_options |
A list of class |
When lag == max_lag (the default), an equi-join is used: source dates
are shifted forward by lag and matched exactly. When lag < max_lag,
an inequality join is used: for each row, the most recent source value
within the window [date - max_lag, date - lag] is selected.
The combination of by and date columns must be unique in data. If by
is NULL, dates alone must be unique.
A data frame with the same rows as data and new columns appended,
each suffixed with _lag. Unmatched rows receive NA in the lagged
columns.
Other rolling and lagging functions:
compute_rolling_value(),
join_lagged_values()
set.seed(42)
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)
)
# Exact lag: each row gets the value from exactly 2 months earlier
add_lagged_columns(
data,
cols = c("size", "bm"),
lag = months(2),
by = "permno"
)
# Window lag: each row gets the most recent value from 2 to 4 months earlier
add_lagged_columns(
data,
cols = "size",
lag = months(2),
max_lag = months(4),
by = "permno"
)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.