Learn R Programming

Westerlund (version 0.1.2)

get_ts_val: Strict Time-Series Mapping with Explicit Gaps

Description

Retrieves lagged (or led) values from a time-indexed vector using a strict time-based mapping.

Usage

get_ts_val(vec, tvec, lag)

Value

A vector of the same length as vec, containing the lagged (or led) values aligned by time index. Elements are NA when the requested time period does not exist.

Arguments

vec

A numeric (or atomic) vector of observations.

tvec

A vector of time indices corresponding one-to-one with vec. Values must uniquely identify time periods within the series.

lag

Integer. The lag order. Positive values correspond to lags (e.g., lag = 1 for \(t-1\)), while negative values correspond to leads (e.g., lag = -1 for \(t+1\)).

Implementation Details

This section explains why get_ts_val() is useful and how it differs from standard lagging approaches based on vector positions.

Why strict time-based lagging matters

In panel and time-series econometrics, lagged variables should be defined with respect to the time index, not the row position. When data contain gaps in time, simple shifting (e.g., c(NA, x[-length(x)])) can produce incorrect values. get_ts_val() avoids this by explicitly matching on time values.

Relation to Stata operators

This function replicates the behaviour of Stata’s time-series operators:

  • L.x: lagged value at \(t-1\),

  • L2.x: lagged value at \(t-2\),

  • F.x: lead value at \(t+1\).

When time periods are missing, Stata returns missing values rather than shifting across gaps.

Details

This helper function implements a strict time-based lookup rather than position-based indexing. Internally, it constructs a named mapping from time indices to observed values:


val_map <- setNames(vec, tvec)

For each observation at time \(t\), the function computes the target time \(t - \text{lag}\) and retrieves the corresponding value from the map.

If the target time does not exist in tvec, the function returns NA for that observation. This behaviour exactly mirrors Stata’s lag/lead operators in the presence of gaps.

Importantly, the function does not interpolate or shift values when time periods are missing. A gap in the time index propagates as NA in the lagged (or led) series.

See Also

westerlund_test, calc_lrvar_bartlett

Examples

Run this code
## Example 1: Regular time series
t <- 1:5
x <- c(10, 20, 30, 40, 50)

## Lag by one period
get_ts_val(x, t, lag = 1)
# [1] NA 10 20 30 40

## Lead by one period
get_ts_val(x, t, lag = -1)
# [1] 20 30 40 50 NA

## Example 2: Time series with a gap
t_gap <- c(1, 2, 4, 5)
x_gap <- c(10, 20, 40, 50)

## Lag by one period: note the NA at time 4
get_ts_val(x_gap, t_gap, lag = 1)
# [1] NA 10 NA 40

## Explanation:
## - At t = 4, t - 1 = 3 does not exist in t_gap, so NA is returned.

## Example 3: Higher-order lags
get_ts_val(x_gap, t_gap, lag = 2)
# [1] NA NA NA 20

Run the code above in your browser using DataLab