Last active
October 22, 2017 05:39
-
-
Save page1/824fb99b0ad630d245e54de2486bcf9b to your computer and use it in GitHub Desktop.
Function to easily add lagged variables to a data.table timeseries
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# data must be a data.table | |
# lags is a vector of positive integer lags | |
add_lag_variables <- function(data, lags){ | |
setkey(data, ticker_id, timestamp) | |
setorder(data, ticker_id, timestamp) | |
col_to_lag <- names(data) | |
col_to_lag <- col_to_lag[!(col_to_lag %in% c('ticker_id', 'timestamp'))] | |
for(lag in lags){ | |
lag_col_names <- paste(col_to_lag, "lag", lag, sep = "_") | |
data[,(lag_col_names) := shift(.SD, n = lag, type = 'lag'), by = ticker_id, .SDcols = col_to_lag] | |
} | |
return(NULL) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Blog regarding this http://www.currencyprospector.com/2017/10/quickly-create-many-lagged-time-series.html