我正在尝试使用 R 中的
plm
运行双向固定效应面板回归。首先,我随机生成一些数据。然后,我创建时间和公司索引(在面板数据集中像往常一样进行双向索引)和感兴趣的解释变量(zp.dummy
)。然后我创建一个面板数据框。然后我尝试通过 plm
: 拟合双向固定效应面板回归
library(plm)
set.seed(0); z=rnorm(40) # generate random data
ztime=rep(c(1:10),4) # time index
zp.dummy=as.numeric(ztime>5) # a dummy to distinguish first 5 from last 5 time periods
zfirm=rep(sequence(4), each=10) # firm index
zp.rete=pdata.frame(cbind(ztime,zfirm,zp.dummy,z),index=c("ztime","zfirm"))
# create panel data frame indexed by time and firm
colnames(zp.rete)[4]="zp.rete" # rename a column in the panel data frame
zm1p=plm(zp.rete~zp.dummy, data=zp.rete, index=c("ztime","zfirm"), model="within", effect="twoways")
# run the panel regression via `plm`
运行最后一行时,我收到此错误消息:
> Error in plm.fit(data, model, effect, random.method, random.models, random.dfcor, :
empty model
问题:我做错了什么?
我想我可以通过
lm
达到想要的结果:
zftime=as.factor(ztime) # turn time index into factor
zffirm=as.factor(zfirm) # turn firm index into factor
zm1 = lm(zp.rete$zp.rete~-1+zp.dummy+zffirm+zftime)
# two-way fixed effects regression via `lm`
如何通过
lm
复制 plm
的结果?
通过
lm
仔细查看模型的输出:您会注意到,因子的水平是不可估计的(是NA
)。那是因为数据中没有足够的信息。
# NA coefficient:
summary(zm1)
model.matrix(zm1) ## looks suspicious
plm::detect.lindep(model.matrix(zm1)) ## collinear columns
现在,为什么plm会输出错误?它首先转换数据(转换内的双向),然后对转换结果运行简单的线性回归,右侧称为模型矩阵。我们还可以查看模型矩阵(转换后的数据),并会注意到,我们最终得到一个仅零的列。显然,只有一个零列的模型是不可估计的,因此,plm 错误是正确的。
library(plm)
set.seed(0); z <- rnorm(40) # generate random data
ztime <- rep(c(1:10),4) # time index
zp.dummy <- as.numeric(ztime>5) # a dummy to distinguish first 5 from last 5 time periods
zfirm <- rep(sequence(4), each=10) # firm index
zp.data <- pdata.frame(cbind(ztime, zfirm, zp.dummy, z),index=c("zfirm", "ztime"))
# create panel data frame indexed by time and firm
colnames(zp.data)[4] <- "zp.rete" # rename a column in the panel data frame
# create model frame
mf <- model.frame(zp.data, zp.rete ~ zp.dummy)
# create model matrix
mm <- model.matrix(mf, model = "within", effect = "twoways")
all(mm == 0) # TRUE