Learn R Programming

mStats (version 3.4.0)

lag.data.frame: Lag a variable

Description

creates lagged version of an existing variable.

Usage

# S3 method for data.frame
lag(x, var, by = NULL, new_var = NULL, last_obs = FALSE, ...)

Arguments

x

data.frame

var

variable to be lagged

by

variable for grouped lagged version

new_var

name of new lagged variable

last_obs

TRUEretrieves the last observation per group.

...

further arguments to be passed to or from methods.

Value

data.frame

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 {
set.seed(100)
## create a dataset with dates
x <- data.frame(
    hospid = 1:100,
    docid = round(runif(100, 1, 10)),
    dis_date = formatDate(runif(100, 42700, 42800))
)

## lagged dis_date, not specifed "by"
lag(x, dis_date)

# }
# NOT RUN {
## lagged dis_date by docid
## first we need to sort
y <- x[order(x$docid), ]
y

## lag dates within groups
lag(y, dis_date, by = docid, new_var = lag_date)
lag(y, dis_date, by = docid, lag_date, TRUE)
# }
# NOT RUN {
# }

Run the code above in your browser using DataLab