在事件之前和之后定义虚拟对象

问题描述 投票:0回答:1

我有一个发生在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等于1(事件发生)之前10个月发生事件时在“t-10”列中创建值1,依此类推,直到t + 10。

r time dummy-variable economics
1个回答
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

© www.soinside.com 2019 - 2024. All rights reserved.