Stata中依据year变量动态匹配x年份变量生成新变量X的技术问询
问题描述
我有一份个体数据集,每个个体在不同年份和国家被观测。现有自变量x2002、x2010(见下方Dataex示例:Before),存储特定国家对应年份的变量X值。例如,2002年法国的所有个体x2002值为10,x2010值为200。我需要创建新变量X,每行的X值需匹配变量名中包含对应year变量值的变量的单元格值。原始数据集包含x2002至x2018的变量,共10万条观测,因此需要自动化实现。我是Stata新手,期望结果见Dataex示例:After。
Dataex示例:After
* Example generated by -dataex-. For more info, type help dataex clear input int id str6 country int(year y1) float(y2 x2002 x2010 x) 7 "France" 2002 7 1.8628873 10 200 10 5 "France" 2002 2 19.52281 10 200 10 6 "France" 2010 7 14.80233 15 500 500 8 "France" 2010 9 15.173367 15 500 500 3 "USA" 2002 8 2.2806208 5 100 5 1 "USA" 2002 6 18.706757 5 100 5 4 "USA" 2010 4 7.421789 30 25 25 2 "USA" 2010 4 9.642876 30 25 25 end
Dataex示例:Before
* Example generated by -dataex-. For more info, type help dataex clear input int id str6 country int(year y1) float(y2 x2002 x2010) 7 "France" 2002 7 1.8628873 10 200 5 "France" 2002 2 19.52281 10 200 6 "France" 2010 7 14.80233 15 500 8 "France" 2010 9 15.173367 15 500 3 "USA" 2002 8 2.2806208 5 100 1 "USA" 2002 6 18.706757 5 100 4 "USA" 2010 4 7.421789 30 25 2 "USA" 2010 4 9.642876 30 25 end
我当前尝试的代码(无法实现需求):
foreach i in year { gen x = list x`i' in i }
不清楚如何实现动态选择变量。
解决方案
针对你的需求,有两种简洁高效的自动化实现方式,适合处理大样本数据:
方法1:使用条件判断批量赋值(直观易理解)
如果年份是固定的2002、2004…2018,可直接用条件判断生成目标变量:
gen x = . replace x = x2002 if year == 2002 replace x = x2004 if year == 2004 replace x = x2006 if year == 2006 replace x = x2008 if year == 2008 replace x = x2010 if year == 2010 replace x = x2012 if year == 2012 replace x = x2014 if year == 2014 replace x = x2016 if year == 2016 replace x = x2018 if year == 2018
这种方式逻辑直白,新手容易上手,执行效率也很高。
方法2:动态循环匹配变量名(通用自动化方案)
如果年份范围不确定或变量较多,可通过循环自动识别年份并赋值:
* 提取所有以x20开头的变量名 unab x_vars: x20* * 去掉变量名里的x,得到纯年份列表 local years: subinstr local x_vars "x" "", all * 初始化x变量 gen x = . * 循环每个年份,匹配赋值 foreach y of local years { replace x = x`y' if year == `y' }
代码说明:
unab x_vars: x20*:提取所有以x20开头的变量名,存入本地宏x_varslocal years: subinstr local x_vars "x" "", all:移除变量名中的x,得到纯年份数字的列表- 循环遍历每个年份,判断当前行的
year是否匹配,匹配则将对应x年份变量的值赋给x
这种方法无需手动列出所有年份,完全适配你的x2002到x2018变量,适合大样本场景。
内容的提问来源于stack exchange,提问作者flxflks
相关产品推荐
相关产品推荐

