3

我基于具有一堆单位固定效应的“巨型”面板数据进行了回归。所以我使用了包“lfe”中的函数“felm()”。另外,我在回归中有两个连续变量的交互项。但是在绘制 x 对 y 的边际效应如何随 x2 变化时,似乎“felm()”生成的对象通常与“ggplot”、“interplot()”和“meplot”等大多数绘图函数不兼容。但是我必须使用“felm()”,因为我需要控制大量的单位固定效果(就像人们在 Stata 中通过“reghdfe”所做的那样)。那么,我如何在 R 中解决这个问题呢?随时让我知道一些出路。谢谢!

下面是一个关于 interplot() 如何不能与 felm() 一起使用的示例:

# An example data:
library(lfe)
library(ggplot2)
library(interplot)
oldopts <- options(lfe.threads=1)
x <- rnorm(1000)
x2 <- rnorm(length(x))
id <- factor(sample(10,length(x),replace=TRUE))
firm <- factor(sample(3,length(x),replace=TRUE,prob=c(2,1.5,1)))
year <- factor(sample(10,length(x),replace=TRUE,prob=c(2,1.5,rep(1,8))))
id.eff <- rnorm(nlevels(id))
firm.eff <- rnorm(nlevels(firm))
year.eff <- rnorm(nlevels(year))
y <- x + 0.25*x2 + id.eff[id] + firm.eff[firm] +
  year.eff[year] + rnorm(length(x))
mydata <- data.frame(cbind(y, x, x2, id, firm, year))

# Regression using felm():
reg1 <- felm(y ~ x + x2 + x:x2|id+firm+year|0|id, data=mydata)
summary(reg1)

# Using interplot() to plot marginal effects
interplot(m=reg1, var1="x", var2="x2", ci=0.9)

然后出现错误:

Error in (function (classes, fdef, mtable)  : 
  unable to find an inherited method for function ‘sim’ for signature ‘"felm"’

我也试过 meplot() 但它仍然不起作用:

# Using meplot() to plot marginal effects
library(evir)
meplot(model=reg1, var1="x", var2="x2", int="x:x2", vcov=vcov(reg1), data=mydata)

我收到一个错误:

Error in meplot(model = reg1, var1 = "x", var2 = "x2", int = "x:x2", vcov = vcov(reg1),  : 
  (list) object cannot be coerced to type 'double'
4

1 回答 1

3

我已经使用并实现了我想要的ggplot2,用手绘制边际效应。coef()vcov()

library(ggplot2)
beta.hat <- coef(reg1)
vcov1 <- vcov(reg1)
z0 <- seq(min(x2), max(x2), length.out = 1000)
dy.dx <- beta.hat["x"] + beta.hat["x:x2"]*z0
se.dy.dx <- sqrt(vcov1["x", "x"] + (z0^2)*vcov1["x1:x2", "x1:x2"] + 2*z0*vcov1["x", "x1:x2"])
upr <- dy.dx + 1.96*se.dy.dx
lwr <- dy.dx - 1.96*se.dy.dx
ggplot(data=NULL, aes(x=z0, y=dy.dx)) +
  labs(x="x2", y="Marginal Effects",
       title=paste("Marginal Effects of x on y vary with x2"), 
       cex=4) +
  geom_line(aes(z0, dy.dx),size = 1) +
  geom_line(aes(z0, lwr), size = 1, linetype = 2, color="blue") +
  geom_line(aes(z0, upr), size = 1, linetype = 2, color="blue") +
  geom_hline(yintercept=0, size = 1, linetype=3) +
  geom_ribbon(aes(ymin=lwr, ymax=upr), alpha=0.3)
于 2019-12-09T03:54:49.627 回答