lag.data.frame {mStats} | R Documentation |
Lag a variable
Description
creates lagged version of an existing variable.
Usage
## 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 |
|
... |
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
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)
[Package mStats version 3.4.0 Index]