| shiftNA | R Documentation |
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.
shiftNA(v, k)
v |
A vector (numeric, character, etc.). |
k |
Integer. Shift order. Positive values correspond to lags
(shifting the series downward, i.e.\ |
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}
A vector of the same length as v, containing the shifted values
with NA inserted where the shift would otherwise go out of range.
This section explains the implications of using NA padding in
recursive or difference-based calculations.
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.
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.
WesterlundBootstrap,
get_lag,
get_diff
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
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.