add_lagged_columns: Add Lagged Columns via Join

View source: R/add_lagged_columns.R

add_lagged_columnsR Documentation

Add Lagged Columns via Join

Description

Appends lagged versions of specified columns to a data frame using a join-based approach.

Usage

add_lagged_columns(
  data,
  cols,
  lag,
  max_lag = lag,
  by = NULL,
  drop_na = FALSE,
  ff_adjustment = FALSE,
  data_options = NULL
)

Arguments

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⁠.

lag

An integer or a lubridate::periods() object, e.g., months(1), specifying the minimum lag (inclusive) to apply.

max_lag

An integer or a lubridate::periods() object specifying the maximum lag (inclusive) to apply. Defaults to lag (exact lag).

by

An optional character vector specifying grouping columns (e.g., a stock identifier). Lagged values are matched within groups. Defaults to NULL.

drop_na

A logical value. If TRUE, NA values in the source columns are excluded before matching, so the lookup skips over missing observations. Applied independently per column. Defaults to FALSE.

ff_adjustment

A logical value. If TRUE, only the last observation per year (within each group defined by by) is retained as a source for lagged values, following Fama-French conventions for annual accounting data. Defaults to FALSE.

data_options

A list of class tidyfinance_data_options (created via data_options()) specifying column name mappings. The date element is used to specify the date column. Uses data_options() default if NULL: "date" = "date".

Details

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.

Value

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.

See Also

Other rolling and lagging functions: compute_rolling_value(), join_lagged_values()

Examples

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"
)


tidyfinance documentation built on July 3, 2026, 1:09 a.m.