【问题标题】:How to run coeftest() across multiple regression models?如何跨多个回归模型运行 coeftest()?
【发布时间】:2021-04-22 10:20:01
【问题描述】:

我使用 purrr 包为两个不同的模型运行回归模型。第一个模型是"sales + cpi",第二个模型是“sales + ndi"。两个模型的因变量是价格。下面的代码显示了我如何在三个不同区域运行这两个模型的回归。

我的问题是如何添加coeftest() 作为循环的第二步。这意味着我将为三个区域的每个回归添加coeftest()。我将在第二步中展示如何为一个模型执行此操作。

我尝试使用map2()coeftest() 包含在purrr package 中,但我无法将它集成到循环函数中。有人可以帮忙吗?

在下面的第一步中,我将展示如何跨区域运行多重回归:

    library(plm)
    library(lmtest)
    library(broom)
    library(purrr)
    library(dplyr)

    data(Cigar)
    Cigar$region = rbinom(n=1380, size=3, prob=0.5)
    Cigar$region = as.factor(Cigar$region)
    
  model_by_region= Cigar %>%
  ungroup()  %>%
  nest_by(region) %>%
  mutate(model = list(map(c
                          (  "sales + cpi",
                            "sales+ ndi"), ~
                            cbind(model = .x, tidy(plm(formula(paste0("price ~ ", .x)), 
                                                       index=c("state", "year"), model="within", data = data),  conf.int=TRUE))))) 

在第二步中,我将展示如何为一个模型运行 coeftest():

model<- plm(price ~ sales + cpi, index=c("state", "year"), model = 'within', 
                data = Cigar)
    #Extract the robust standard errors    
    plot_coeftest = tidy(coeftest(model))

【问题讨论】:

  • 不确定是否将问题理解为tidy(model) == tidy(coeftest(model)),您可以在上面的最后一个示例中进行测试。您能否详细说明您的目标?
  • 在第一步中,我运行了 4 个不同的回归模型——每个回归模型都是按区域进行的。您可以在model_by_region 中查看它们。我的目标是使用coeftest() 函数为第一步中的 4 个回归中的每一个添加稳健的标准误差。在第二步中,我将展示如何为一个模型执行此操作,但我的目标是在四个区域中自动包含 coeftest()
  • 查看我作为答案发布的扩展评论。如果我误解了你的问题,我会删除它。

标签: r purrr broom


【解决方案1】:

这可能很简单:

model_by_country_with_coef_test = Cigar %>%
  ungroup()  %>%
  nest_by(region) %>%
  mutate(model = list(map(c
                          (  "sales + cpi",
                            "sales+ ndi"), ~
                            cbind(model = .x, tidy(coeftest(plm(formula(paste0("price ~ ", .x)), 
                                                        index=c("state", "year"), model="within", data = data)), conf.int=TRUE
                            )))))




model_by_country_with_coef_test[[3]][[1]]
[[1]]
        model  term   estimate  std.error statistic      p.value   conf.low  conf.high
1 sales + cpi sales -0.4716673 0.04863656 -9.697793 6.831817e-17 -0.5679327 -0.3754019
2 sales + cpi   cpi  1.0209728 0.02336462 43.697376 3.542571e-77  0.9747277  1.0672179

[[2]]
       model  term     estimate    std.error statistic      p.value     conf.low   conf.high
1 sales+ ndi sales -0.267552595 0.0500205394 -5.348855 4.111431e-07 -0.366557254 -0.16854794
2 sales+ ndi   ndi  0.008491882 0.0001944991 43.660261 3.911187e-77  0.008106914  0.00887685

【讨论】:

  • 感谢您的回答。这里的结果相同不是问题,因为当我用我正在使用的真实数据尝试它时它们是不同的。但是,将置信区间包含在coeftest() 中很重要,否则我无法绘制估计值。有办法吗?
  • @jad,查看我的编辑:我确实删除了 conf.int,而不是 conftest。返回 ;-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-16
  • 1970-01-01
  • 1970-01-01
  • 2020-11-23
  • 2023-01-21
  • 1970-01-01
  • 2021-02-18
相关资源
最近更新 更多