Learn R Programming

misty (version 0.5.4)

shift: 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)

Value

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

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.

Author

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

Run this code
#--------------------------------------
# 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)

Run the code above in your browser using DataLab