Learn R Programming

Westerlund (version 0.1.2)

shiftNA: NA-Padded Lag and Lead Operator

Description

Shifts a vector forward or backward by a specified number of positions and fills out-of-range values with NA. This helper is designed for position-based transformations where missing values should be explicitly propagated as NA rather than assumed to be zero.

Usage

shiftNA(v, k)

Value

A vector of the same length as v, containing the shifted values with NA inserted where the shift would otherwise go out of range.

Arguments

v

A vector (numeric, character, etc.).

k

Integer. Shift order. Positive values correspond to lags (shifting the series downward, i.e.\ \(t-k\)), while negative values correspond to leads (shifting the series upward, i.e.\ \(t+k\)).

Usage and Propagation

This section explains the implications of using NA padding in recursive or difference-based calculations.

Why NA-padding?

Using NA is the standard behavior in R for out-of-bounds operations. It ensures that subsequent calculations (like v - shiftNA(v, 1)) correctly result in NA for boundary cases, preventing the accidental use of arbitrary values (like zero) in statistical estimations unless explicitly intended.

Difference from get_lag()

Unlike get_lag, shiftNA() is position-based and ignores time indices. Use shiftNA() when you need a fast, simple shift on vectors that are already correctly ordered.

Details

This function performs a position-based shift of the input vector v. Unlike strict time-indexed helpers (such as get_lag), shiftNA() does not rely on an explicit time index and does not propagate gaps based on timestamps. Instead, it performs a simple index shift, padding the resulting empty slots with NA.

Let \(n\) denote the length of v. The behaviour is:

  • k = 0: return v unchanged,

  • k > 0: lag by k positions; the first k elements are NA,

  • k < 0: lead by \(|k|\) positions; the last \(|k|\) elements are NA.

Formally, for k > 0, $$ \text{out}_t = \begin{cases} \text{NA}, & t \le k, \\ v_{t-k}, & t > k, \end{cases} $$ and for k < 0, $$ \text{out}_t = \begin{cases} v_{t+|k|}, & t \le n-|k|, \\ \text{NA}, & t > n-|k|. \end{cases} $$

See Also

WesterlundBootstrap, get_lag, get_diff

Examples

Run this code
v <- c(1, 2, 3, 4, 5)

## Lag by one (k = 1)
shiftNA(v, 1)
# [1] NA 1 2 3 4

## Lead by one (k = -1)
shiftNA(v, -1)
# [1] 2 3 4 5 NA

## Larger shifts
shiftNA(v, 2)
# [1] NA NA 1 2 3

shiftNA(v, -2)
# [1] 3 4 5 NA NA

Run the code above in your browser using DataLab