You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在R中对教育健康面板数据执行面板回归及错误解决

解决面板回归0样本错误及后续操作

1. 先修复子集筛选的低级错误

你代码里先把Indicator中的"Perceived health"替换成了"Perceived_health",后面子集筛选却还用Indicator == "Perceived health",这直接导致筛选不到任何数据,肯定会触发0样本错误。二选一修正:

# 方案1:不做字符串替换,直接用原指标名筛选
perceived_health_data <- subset(education, Indicator == "Perceived health")

# 方案2:替换后用新指标名筛选
education$Indicator <- gsub("Perceived health", "Perceived_health", education$Indicator)
perceived_health_data <- subset(education, Indicator == "Perceived_health")

2. 检查数据结构与变量有效性

修复筛选后,还要确认两个核心问题:

  • 你的perceived_health_data里是否同时有Value(健康指标)和Education变量的有效非NA值?如果Education在健康指标的行里全是NA,依然会出现0样本错误。
  • 你的数据是不是长格式转宽格式的问题?如果健康和教育是分不同Indicator存储的(比如一行是某国某年的健康数据,另一行是同国同年的教育数据),必须先转成宽格式,让同一国家年份的健康和教育值在同一行:
# 用tidyr包转宽格式,假设个体标识是Country列,时间标识是Time列
library(tidyr)
wide_data <- pivot_wider(education, 
                         id_cols = c(Country, Time), 
                         names_from = Indicator, 
                         values_from = Value)

# 转完后直接用健康指标做因变量、教育指标做自变量跑模型
model <- plm(Perceived_health ~ Education, data = wide_data, model = "within", index = c("Country", "Time"))
summary(model)

3. 关于虚拟变量的问题

面板回归的within模型会自动控制个体固定效应(相当于给每个国家自动生成虚拟变量),不需要手动创建个体虚拟变量。如果需要同时控制时间固定效应,直接在模型里设置双向固定效应即可:

# 双向固定效应模型(控制国家+时间固定效应)
model <- plm(Perceived_health ~ Education, data = wide_data, model = "within", index = c("Country", "Time"), effect = "twoways")

4. 额外排查步骤

  • 用str(wide_data)查看变量类型,Time不需要强行转成Date格式,用年份数字也能被plm识别。
  • 用na.omit(wide_data)删除含NA的观测行后再跑模型,确认是否是缺失值导致的样本为0。

内容的提问来源于stack exchange,提问作者Agnieszka Kowalska

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 05:22:41