shifts_by: Shift Data (i.e., lag/lead) by Group In quest: Prepare Questionnaire Data for Analysis

Description

shifts_by 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 within each group by time such that the first row for that group is earliest in time and the last row for that group is the latest in time. The groups can be specified by multiple columns in data (e.g., grp.nm with length > 1), and interaction will be implicitly called to create the groups.

Usage

 1 shifts_by(data, vrb.nm, grp.nm, n, undefined = NA, suffix)

Arguments

 data data.frame of data. vrb.nm character vector of colnames from data specifying the variables. grp.nm character vector of colnames from data specifying the groups. n integer vector of length 1. Specifies the direction and magnitude of the shift. See details. undefined 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. suffix 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("_gw", -n), 2) if n > 0, then suffix = paste0("_dw", +n), 3) if n = 0, then suffix = "".

Details

If n is negative, then shifts_by inserts undefined into the first abs(n) rows of data[vrb.nm] for each group, 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 each group. If n is positive, then shifts_by drops the first abs(n) rows of x for each group, 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 each group. If n is zero, then shifts_by simply returns data[vrb.nm].

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

Value

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