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

如何在Stata/R中按国家生成缺失年份变量完成数据集合并

双数据集合并补全年份变量方案

以下分别提供Stata和R两种工具的实现代码:

Stata实现

场景1:带完整年份的数据集所有观测年份一致(标准单期横截面)

  • 提取公共年份值:
use "full_data.dta", clear
* 若年份为数值型
sum year, meanonly
local common_year = r(mean)
* 若年份为字符串型,替换为下面这行
* levelsof year, local(common_year)
  • 给缺失年份的数据集补全年份:
use "missing_year_data.dta", clear
gen year = `common_year'
  • 按国家+年份双主键合并:
merge 1:1 country year using "full_data.dta", nogen

场景2:完整数据集内每个国家对应唯一的不同年份

  • 先提取国家-年份映射表:
use "full_data.dta", clear
keep country year
save "country_year_link.dta", replace
  • 给缺失年份的数据集匹配对应年份:
use "missing_year_data.dta", clear
merge 1:1 country using "country_year_link.dta", keep(match) nogen
  • 双主键合并两个数据集:
merge 1:1 country year using "full_data.dta", nogen

R实现

场景1:带完整年份的数据集所有观测年份一致(标准单期横截面)

tidyverse写法

library(tidyverse)
# 提取公共年份
common_year <- unique(full_data$year)
# 补全年份
missing_year_data <- missing_year_data %>% 
  mutate(year = common_year)
# 双主键合并
merged_data <- inner_join(full_data, missing_year_data, by = c("country", "year"))

基础R写法

# 提取公共年份
common_year <- unique(full_data$year)
# 补全年份
missing_year_data$year <- common_year
# 双主键合并
merged_data <- merge(full_data, missing_year_data, by = c("country", "year"))

场景2:完整数据集内每个国家对应唯一的不同年份

tidyverse写法

library(tidyverse)
# 提取国家-年份映射
country_year_map <- full_data %>% select(country, year)
# 匹配补全年份
missing_year_data <- missing_year_data %>% 
  left_join(country_year_map, by = "country")
# 双主键合并
merged_data <- inner_join(full_data, missing_year_data, by = c("country", "year"))

基础R写法

# 提取国家-年份映射
country_year_map <- full_data[,c("country", "year")]
# 匹配补全年份
missing_year_data <- merge(missing_year_data, country_year_map, by = "country", all.x = T)
# 双主键合并
merged_data <- merge(full_data, missing_year_data, by = c("country", "year"))

注意:如果完整数据集存在单个国家对应多个年份的情况,需先根据研究需求筛选每个国家对应的目标年份后再执行上述操作

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 15:24:03