如何在Stata中将长格式数据集转换为指标行年份列的宽表
Stata长表转指定结构宽表及Excel导出操作指南
前置说明
你当前的数据集为标准长表结构:每条观测对应单个国家+单一年份的3个指标值,字段为Country、Year、Indicator 1、Indicator 2、Indicator 3。你需要的最终宽表为「国家+指标」作为行维度、年份作为列维度,需要分两步完成reshape操作。
操作步骤
步骤1:预处理变量名
Stata变量名不支持空格,先对带空格的指标字段重命名:
rename "Indicator 1" ind1 rename "Indicator 2" ind2 rename "Indicator 3" ind3
步骤2:将横向排列的指标转为纵向排列
把3个指标列转为「指标名+指标值」的两列结构,为后续转年份列做准备:
* i()指定唯一标识单条观测的字段,j()生成指标名标识列,string指定j列为字符串格式 reshape long ind, i(Country Year) j(indicator) string * 可按需将indicator列的取值替换为原指标名称 replace indicator = "Indicator 1" if indicator == "1" replace indicator = "Indicator 2" if indicator == "2" replace indicator = "Indicator 3" if indicator == "3"
执行完成后,数据集结构变为:每条观测对应单个国家+单一年份+单个指标的数值,共4个字段:Country、Year、indicator、ind。
步骤3:将纵向排列的年份转为横向列
以国家、指标为行维度,把年份转为列存放对应指标值:
* i()指定行维度字段,j()指定要转成列的年份字段 reshape wide ind, i(Country indicator) j(Year)
执行完成后即可得到目标结构:
- 前两列为
Country、indicator,对应行维度 - 后续每列对应一个年份,列名为
ind1950、ind1951...,存放对应指标值
如果需要列名直接显示为年份,可执行批量重命名:
foreach var of varlist ind* { local year = substr("`var'",4,.) rename `var' `year' }
步骤4:导出到Excel
* 替换为你自己的输出路径,firstrow指定把变量名作为Excel第一行表头 export excel using "C:/你的文件夹/宽表结果.xlsx", firstrow(variables) replace
注意事项
- 执行reshape前如果报错「观测不唯一」,先执行去重命令:
duplicates drop Country Year indicator, force - 年份范围在1950至今的场景下,列数不会超过Excel的最大列数限制,可正常导出
内容的提问来源于stack exchange,提问作者yetona9756
相关产品推荐
相关产品推荐

