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

如何构建平衡面板数据,仅保留所有年份均存在的观测值

R语言构建平衡面板(保留所有年份均有观测的个体)解决方案

核心思路:先计算数据集覆盖的总年份数量,再按个体分组筛选,仅保留观测年份数量和总年份数量一致的个体的所有记录。

方法1:dplyr 实现(代码易读,适合中小规模数据集)

library(dplyr)

# 计算数据集包含的总年份数
total_year_cnt <- n_distinct(df$Year)

balanced_panel <- df %>%
  group_by(variable) %>%
  # 仅保留观测年份数等于总年份数的个体
  filter(n_distinct(Year) == total_year_cnt) %>%
  ungroup()

方法2:data.table 实现(运行效率高,适合大规模数据集)

针对大样本数据优先使用该方案,内存占用和执行速度都有显著优势:

library(data.table)
setDT(df) # 将数据框转为data.table格式

total_year_cnt <- uniqueN(df$Year)
balanced_panel <- df[, .SD[uniqueN(Year) == total_year_cnt], by = variable]

方法3:基础R实现(无需加载第三方包)

total_year_cnt <- length(unique(df$Year))
# 筛选符合要求的个体ID
keep_var <- as.integer(names(which(tapply(df$Year, df$variable, function(x) length(unique(x))) == total_year_cnt)))
# 提取对应行
balanced_panel <- df[df$variable %in% keep_var, ]

以上三种方法输出结果均和你给出的预期结果完全匹配。


内容的提问来源于stack exchange,提问作者Nuñes

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 13:33:03