[英]R - How do I lag/lead multiple columns in a data.table by multiple periods most efficiently
有一個大的 data.table 存儲一個日期列(每月),然后在各個日期為各種主題/ID 測量一堆不同的感興趣變量。 現在,我想為這些變量的一個子集(僅一些列)添加新計算的列,這些列同時領先和滯后這些列多個時期。 那可行嗎? 請參閱下面的一些示例數據的說明,這些示例數據代表了我的表的高級結構以及我迄今為止嘗試過的內容
Date ID Var_A Var_B Var_C
2000-01-31 1 100 500 1000
2000-02-28 1 200 600 1100
2000-03-31 1 300 700 1200
2000-04-30 1 400 800 1300
2000-01-31 2 100 500 1000
2000-02-28 2 200 600 1100
2000-03-31 2 300 700 1200
2000-04-30 2 400 800 1300
dt[, `:=`(Var_A_Lag_1 = shift(Var_A_Lag_1, 1),
Var_A_Lead_1 = shift(Var_A_Lead_1, 1, type = 'lead'),
Var_A_Lag_2 = shift(Var_A_Lag_1, 2),
Var_A_Lead_2 = shift(Var_A_Lead_1, 2, type = 'lead'),
Var_B_Lag_1 = shift(Var_B_Lag_1, 1),
Var_B_Lead_1 = shift(Var_B_Lead_1, 1, type = 'lead'),
Var_B_Lag_2 = shift(Var_B_Lag_1, 2),
Var_B_Lead_2 = shift(Var_B_Lead_1, 2, type = 'lead')),
by = ID]
但這不能有效嗎? 我嘗試了一些我認為非常直觀並且可以工作但沒有運氣的東西。
cols_to_edit <- which(sapply(dt, is.numeric))
cols_to_edit <- colnames(dt[, cols_to_edit, with = FALSE])
# col names od shifted variables
col_names_lag_1 <- paste(cols_to_edit, "lag_1", sep = "_")
col_names_lag_2 <- paste(cols_to_edit, "lag_2", sep = "_")
col_names_lead_1 <- paste(cols_to_edit, "lead_1", sep = "_")
col_names_lead_2 <- paste(cols_to_edit, "lead_2", sep = "_")
# colnames for differences
col_names_lag_1_d <- paste("d", cols_to_edit, "lag_1", sep = "_")
col_names_lag_2_d <- paste("d", cols_to_edit, "lag_2", sep = "_")
col_names_lead_1_d <- paste("d", cols_to_edit, "lead_1", sep = "_")
col_names_lead_2_d <- paste("d", cols_to_edit, "lead_2", sep = "_")
# Execute the shift command
dt_2[, (col_names_lag_1) := shift(cols_to_edit, 1), by = ID]
# would have repeated for all new columns as defined above but it is not working.
我基本上希望該表中的所有數字變量在任一方向上分別移動 1 和 2。 然后應將新計算的值分配給由上面聲明的名稱向量命名的列。 在這里沒有找到與我的情況類似的任何其他問題。 你有什么想法或知道這樣做的最佳實踐嗎?
上下文:變量是選擇的指標作為回歸 model 的輸入,要求輸入以該格式可用。
這在一個不錯的小for
循環中如何:
cols <- grep("Var", names(dt), value = TRUE)
for ( i in 1:2 ) { # update for the number of shifts
lag_names <- paste(cols, "Lag", i, sep = "_")
dt[, (lag_names) := lapply(.SD, shift, i, type = "lag"), .SDcols = cols]
lead_names <- paste(cols, "Lead", i, sep = "_")
dt[, (lead_names) := lapply(.SD, shift, i, type = "lead"), .SDcols = cols]
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.