您可以在 plm 命令之前使用 pdata.frame()(plm.data() 已过时)或更简单(与 Stata 不同)在 plm() 调用本身中执行此操作。 例子:
library(plm)
data("Grunfeld", package="plm")
class(Grunfeld)
# [1] "data.frame"
head(Grunfeld, 3)
# firm year inv value capital
# 1 1 1935 317.6 3078.5 2.8
# 2 1 1936 391.8 4661.7 52.6
# 3 1 1937 410.6 5387.1 156.9
plm 期望前两列是组和时间数据。因此,当您使用上面的 Grunfeld 示例数据进行 FE 回归而不指定索引时,它将起作用。
wi1 <- plm(inv ~ value + capital,
data=Grunfeld, model="within", effect="twoways")
wi1$coe
# value capital
# 0.1177159 0.3579163
但是,当您混淆列时,会发生错误。
## confuse columns
Grunfeld2 <- Grunfeld[c(3:5, 2,1)]
head(Grunfeld2, 3)
# inv value capital year firm
# 1 317.6 3078.5 2.8 1935 1
# 2 391.8 4661.7 52.6 1936 1
# 3 410.6 5387.1 156.9 1937 1
plm(inv ~ value + capital,
data=Grunfeld2, model="within", effect="twoways")
# Error in plm.fit [...]
我们需要在plm调用中指定index=c(<group>, <time>),
wi2 <- plm(inv ~ value + capital, index=c("firm", "year"),
data=Grunfeld2, model="within", effect="twoways")
wi2$coe
# value capital
# 0.1177159 0.3579163
或通过生成"pdata.frame"。
Grunfeld3 <- pdata.frame(Grunfeld2, index=c("firm", "year"))
class(Grunfeld3)
# [1] "pdata.frame" "data.frame"
列的顺序不会改变,index 而是存储在属性中。您可能需要比较 attributes(Grunfeld2) 和 attributes(Grunfeld3)。
wi3 <- plm(inv ~ value + capital,
data=Grunfeld3, model="within", effect="twoways")
wi3$coe
# value capital
# 0.1177159 0.3579163
wi1、wi2 和 wi3 的结果相同。不过会有一些后果,因为 "pdata.frame" 的行名对应于 group-time:
head(Grunfeld3, 3)
# inv value capital year firm
# 1-1935 317.6 3078.5 2.8 1935 1
# 1-1936 391.8 4661.7 52.6 1936 1
# 1-1937 410.6 5387.1 156.9 1937 1
因此,all.equal 抛出字符串不匹配,
all.equal(wi2, wi3)
# [1] "Component “residuals”: Names: 200 string mismatches"
# [2] "Component “model”: Attributes: < Component “row.names”: 200 string mismatches >"
# [3] "Component “call”: target, current do not match when deparsed"
但值是相同的:
head(wi2$residuals)
# 1 2 3 4 5 6
# 41.10980 -69.68476 -152.11391 -19.73566 -93.36168 -28.48560
head(wi3$residuals)
# 1-1935 1-1936 1-1937 1-1938 1-1939 1-1940
# 41.10980 -69.68476 -152.11391 -19.73566 -93.36168 -28.48560
head(wi2$model, 3)
# inv value capital
# 1 317.6 3078.5 2.8
# 2 391.8 4661.7 52.6
# 3 410.6 5387.1 156.9
head(wi3$model, 3)
# inv value capital
# 1-1935 317.6 3078.5 2.8
# 1-1936 391.8 4661.7 52.6
# 1-1937 410.6 5387.1 156.9
wi2$call
# plm(formula = inv ~ value + capital, data = Grunfeld2, effect = "twoways",
# model = "within", index = c("firm", "year"))
wi3$call
# plm(formula = inv ~ value + capital, data = Grunfeld3, effect = "twoways",
# model = "within")