如何在 lm() 中制定时间段虚拟变量

How to formulate time period dummy variable in lm()

我正在分析 x_t 对 y_t 的影响在特定时间段期间和之后是否不同。 我正在尝试使用 lm():

在 R 中回归以下模型
y_t = b_0 + [b_1(1-D_t) + b_2 D_t]x_t

其中 D_t 是一个虚拟变量,在该时间段内的值为 1,否则为 0。

这个公式可以用lm()吗?

observationNumber <- 1:80
obsFactor <- cut(observationNumber, breaks = c(0,55,81), right =F)
fit <- lm(y ~ x * obsFactor)

例如:

 y = runif(80)
 x = rnorm(80) + c(rep(0,54), rep(1, 26))
 fit <- lm(y ~ x * obsFactor)
 summary(fit)

Call:
lm(formula = y ~ x * obsFactor)

Residuals:
     Min       1Q   Median       3Q      Max 
-0.48375 -0.29655  0.05957  0.22797  0.49617 

Coefficients:
                   Estimate Std. Error t value Pr(>|t|)    
(Intercept)         0.50959    0.04253  11.983   <2e-16 ***
x                  -0.02492    0.04194  -0.594    0.554    
obsFactor[55,81)   -0.06357    0.09593  -0.663    0.510    
x:obsFactor[55,81)  0.07120    0.07371   0.966    0.337    
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 0.3116 on 76 degrees of freedom
Multiple R-squared:  0.01303,   Adjusted R-squared:  -0.02593 
F-statistic: 0.3345 on 3 and 76 DF,  p-value: 0.8004
如果 observationNumber < 55

obsFactor[55,81) 为零,如果它的系数大于或等于您的 $b_0$,则为一。 x:obsFactor[55,81) 是虚拟变量和变量 $x_t$ 的乘积 - 它的系数是您的 $b_2$。 $x_t$ 的系数是您的 $b_1$.