我有一个事件发生在t = 0。我想为t-10,t-9,...,t-2,t-1,t = 0,t + 1,t + 2 ... t + 10创建假人。
我具有以下数据结构:
Date t=0 t-10 t-9 ... t+10
2015-1 0 0 0 0
2015-2 0 0 0 0
2015-3 0 0 0 0
2015-4 1 0 0 0
... 0 0 0 0
2017-12 0 0 0 0
当事件在t = 0之前10个月等于1(事件发生)发生时,我想在“ t-10”列中创建值1,依此类推,直到t + 10。
答案 0 :(得分:0)
这是一种方法。它并不优雅,但可以完成工作:
# generate sample date data to work with
df <- data.frame(
date = seq(from=as.Date("2015-01-01"), to=as.Date("2015-02-28"), by="day"),
stringsAsFactors = FALSE
)
# identify the event of interest
event <- as.Date("2015-01-20")
# create a counter for days before/after event
diff <- df$date - event
df$diff <- ifelse(abs(diff) > 10, -999, paste0("t0", diff))
# turn counter into a set of dummy variables
df <- cbind(df, model.matrix( ~ factor(df$diff)))
# clean up by dropping intercept, and reordering and renaming dummies
df$`(Intercept)` <- NULL
df <- df[ , c(1:2, 4, 12:5, 3, 13:14, 16:23, 15)]
names(df)[3:23] <- c( paste0("tm", 10:1), "te0", paste0("tp",1:10))
我不喜欢-
和+
在变量名中签名,所以我将t-8命名为tm8
,而将t + 3命名为tp3
。 / p>