R语言用stargazer输出三个面板固定效应模型遇报错,求解决
问题描述
我用plm包的within模型拟合了三个含id和年份双重固定效应的面板线性模型:
fixed_YIELD_mean_to_treat.100 <- plm(YIELD_mean_total ~ treated.100 + Nightlight_sum + Population_sum + temp_mean, data= Results, index = c("id", "year"), model = "within") fixed_YIELD_mean_fruits_treat.100<- plm(YIELD_mean_Fruit ~ treated.100 + Nightlight_sum + Population_sum + temp_mean, data= Results, index = c("id", "year"), model = "within") fixed_YIELD_mean_grain_treat.100<- plm(YIELD_mean_Cereal ~ treated.100 + Nightlight_sum + Population_sum + temp_mean, data= Results, index = c("id", "year"), model = "within")
随后尝试用stargazer将三个模型合并输出到HTML文件:
stargazer( fixed_YIELD_mean_to_treat.100, fixed_YIELD_mean_fruits_treat.100, fixed_YIELD_mean_grain_treat.100, type = "html", align = TRUE, omit = c("year", "id"), omit.labels = c("year FE", "id FE"), add.lines= list(c("ID Fixed effects", "Yes", "Yes", "Yes"), c("Time Fixed effects", "Yes", "Yes", "Yes")), out = ".test1.html" )
但触发错误:
Error in if (is.na(s)) { : the condition has length > 1
仅输出两个模型时可正常运行,求三个模型合并输出的解决办法。
解决方法
- 检查模型对象一致性:确认三个plm模型的结构完全匹配,比如
index参数、数据集来源、变量结构无差异。可以用str()查看每个模型的内部结构,对比coefficients、model等核心部分是否一致,避免某模型因数据异常导致结构偏差。 - 调整stargazer参数:原代码中
omit = c("year", "id")可能在多模型场景下引发识别冲突,尝试替换为omit = "fixed"(plm的within模型固定效应会被标记为fixed),或直接移除omit与omit.labels参数,改用keep.stat = c("n", "adj.rsq")保留所需统计量,绕过固定效应的识别问题。 - 更新依赖包:旧版本的plm或stargazer可能存在多模型输出的兼容性bug,运行
update.packages(c("plm", "stargazer"))更新至最新版本后重试。 - 替换输出工具:如果上述方法无效,改用
texreg包替代stargazer,它对plm模型的多模型支持更稳定:library(texreg) htmlreg(list(fixed_YIELD_mean_to_treat.100, fixed_YIELD_mean_fruits_treat.100, fixed_YIELD_mean_grain_treat.100), file = ".test1.html", add.lines = list(c("ID Fixed effects", "Yes", "Yes", "Yes"), c("Time Fixed effects", "Yes", "Yes", "Yes")))
内容的提问来源于stack exchange,提问作者Sulz
相关产品推荐
相关产品推荐

