Learn R Programming

mStats (version 3.2.2)

lagRows: Create lagged variables

Description

lagRows() creates lagged version of existing variables

Usage

lagRows(data, var, by = NULL, lag_var = NULL)

Arguments

data

Dataset

var

Existing variable

by

If specified, lagged variable is created grouped by this variable. If not specified, it is created taking the whole variable.

lag_var

name for lagged variable

Value

Modified Dataset

Details

This is often encountered in time-related analysis. In a lagged variable, values from earlier points in time are placed in later rows of dataset.

Examples

Run this code
# NOT RUN {

## create a dataset with dates
df <- data.frame(
    hospid = 1:100,
    docid = round(runif(100, 1, 10)),
    dis_date = formatDate(runif(100, 42700, 42800))
)

## lagged dis_date, not specifed "by"
lagRows(df, dis_date)

## lagged dis_date by docid
## first we need to sort
df1 <- arrange(df, docid)
df1
lagRows(df1, dis_date, by = docid, lag_var = "lag_date")


# }

Run the code above in your browser using DataLab