shifts: Shift Data (i.e., lag/lead)

Description Usage Arguments Details Value See Also Examples

View source: R/quest_functions.R


shifts shifts rows of data down (n < 0) for lags or up (n > 0) for leads replacing the undefined data with a user-defined value (e.g., NA). The number of rows shifted is equal to abs(n). It is assumed that data[vrb.nm] is already sorted by time such that the first row is earliest in time and the last row is the latest in time.


shifts(data, vrb.nm, n, undefined = NA, suffix)



data.frame of data.


character vector of colnames from data specifying the variables.


integer vector of length 1. Specifies the direction and magnitude of the shift. See details.


atomic vector of length 1 (probably makes sense to be the same typeof as the vectors in data[vrb.nm]). Specifies what to insert for undefined values after the shifting takes place. See details.


character vector of length 1 specifying the string to append to the end of the colnames of the return object. The default depends on the n argument: 1) if n < 0, then suffix = paste0("_g", -n), 2) if n > 0, then suffix = paste0("_d", +n), 3) if n = 0, then suffix = "".


If n is negative, then shifts inserts undefined into the first abs(n) rows of data[vrb.nm], shifting all other rows of x down abs(n) positions, and then dropping the last abs(n) row of data[vrb.nm] to preserve the original nrow of data. If n is positive, then shifts drops the first abs(n) rows of x, shifting all other rows of data[vrb.nm] up abs(n) positions, and then inserts undefined into the last abs(n) rows of x to preserve the original length of data. If n is zero, then shifts simply returns data[vrb.nm].

It is recommended to use L when specifying n to prevent problems with floating point numbers. shifts tries to circumvent this issue by a call to round within shifts if n is not an integer; however that is not a complete fail safe. The problem is that as.integer(n) implicit in shifts truncates rather than rounds.


data.frame of shifted data with colnames specified by suffix.

See Also

shift shifts_by shift_by


shifts(data = attitude, vrb.nm = colnames(attitude), n = -1L)
shifts(data = mtcars, vrb.nm = colnames(mtcars), n = 2L)

quest documentation built on Sept. 10, 2021, 5:07 p.m.

Related to shifts in quest...