lagVarsNested: Lagging variables in nested (multilevel) data

View source: R/preprocessing.R

lagVarsNestedR Documentation

Lagging variables in nested (multilevel) data

Description

Creates extra column(s) with lagged variables according to the order of the data.frame. The argument nestVars describes with regards to which variables the data is nested. The function then creates lagged variables only within each group of the nestVars. This is particularly useful when working with multilevel data, where observations are nested, e.g., within individuals.

Usage

lagVarsNested(
  dat = dat,
  vars,
  nestVars,
  lags = 1,
  diffvars = NULL,
  unit = "secs",
  verbose = T
)

Arguments

dat

data.frame containing the variables to be lagged

vars

names of the columns in the data.frame that should be lagged

nestVars

name(s) of the columns indicating how the data is nested (e.g., ID variable). Currently up to two nestVars are possible.

lags

vector defining the nth lag. Positive values (e.g., 1:2) indicatw the values from the previous rows (e.g., the values from the previous (lag = 1) observation) should be taken. Negative values indicate that the values from the following rows should be taken.

diffvars

names of columns in the data.frame of which the difference to the current row should be taken (this is particularly helpful for dealing with time variables and time differences)

unit

character value, if time variables are being lagged and the difference is taken, which time unit should be used to calculate the difference

verbose

boolean indicating about the state of the process be displayed

Value

data.frame with new columns containing the lagged variables

See Also

lagVars

Examples

dat <- data.frame(ID = c(rep(1,10), rep(2,10)),
                  day = rep(c(rep(1,5), rep(2,5)),2),
                  a = runif(20, max = 10),
                  b = Sys.Date()+1:20,
                  cat = sample(c("X","Y","Z"), 20, replace = T))
lagVarsNested(dat, lags = 1:2, nestVars = c("ID","day"),
                     vars = c("a","b"), diffvars = "b", unit = "days")


timonelmer/dena documentation built on April 15, 2023, 11:51 p.m.