lag: Lag a variable

Description Usage Arguments Details Value Note Author(s) Examples

Description

creates lagged version of an existing variable.

Usage

1
2
## S3 method for class '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.

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.

Value

data.frame

Note

Before using lagRows, the dataset needs to be sorted by a id variable or similar variable.

Author(s)

Email: dr.myominnoo@gmail.com

Website: https://myominnoo.github.io/

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
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)

## End(Not run)

mStats documentation built on Nov. 23, 2020, 9:07 a.m.

Related to lag in mStats...