Skip to content

Instantly share code, notes, and snippets.

@page1
Last active October 22, 2017 05:39
Show Gist options
  • Save page1/824fb99b0ad630d245e54de2486bcf9b to your computer and use it in GitHub Desktop.
Save page1/824fb99b0ad630d245e54de2486bcf9b to your computer and use it in GitHub Desktop.
Function to easily add lagged variables to a data.table timeseries
# 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)
}
@page1
Copy link
Author

page1 commented Oct 22, 2017

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment