shift: Compute lagged or leading values of a vector

View source: R/shift.R

shiftR Documentation

Compute lagged or leading values of a vector

Description

This function computes lagged or leading values of a vector by a specified number of observations. By default, the function returns lag-1 values of the vector specified in the argument 'x'.

Usage

shift(x, n = 1, fill = NA, as.na = NULL, check = TRUE)

Arguments

x

a numeric vector.

n

a numeric value denoting the offset by which to lag (positive value) or lead (negative value), e.g. n = 1 (default) returns lag-1 values, and n = -1 returns lead-1 values of the vector specified in 'x'.

fill

a numeric value or NA (default) used to pad x back to its original size after the lag or lead has been applied.

as.na

a numeric vector indicating user-defined missing values, i.e. these values are converted to NA before computing lagged or leading values of the vector.

check

logical: if TRUE, argument specification is checked.

Value

Returns a numeric vector with the same length containing lagged or leading values.

Note

This function is a modified copy of the lag() and lead() functions in the dplyr package by Wickham et al. (2023).

Author(s)

Hadley Wickham, Romain Francois, Lionel Henry, and Kirill Müller, and Davis Vaughan.

References

Wickham H, Francois R, Henry L, Müller K, & Vaughan D (2023). dplyr: A grammar of data manipulation. R package version 1.1.3, <https://CRAN.R-project.org/package=dplyr>.

See Also

center, rec, dummy.c, item.reverse.

Examples

#--------------------------------------
# Lagged values

# Lag-1 values
shift(1:10)

# Lag-2 values
shift(1:10, n = 2)

# Value -99 to pad 'x'
shift(1:10, fill = -99)

#--------------------------------------
# Leading values

# Lead-1 values
shift(1:10, n = -1)

# Lead-2 values
shift(1:10, n = -2)

misty documentation built on Nov. 15, 2023, 1:06 a.m.

Related to shift in misty...