如何在Stata中根据另一变量值检索行号并替换变量值
在Stata中实现基于变量条件的行索引替换
我明白你想在Stata里实现类似R中方括号索引的操作——通过变量cumul的条件(cumul==20)定位到对应行,再把第12行的country值替换成该行的country值。Stata的索引逻辑和R确实不一样,你原来的写法replace country = country[cumul==20] in 12不符合Stata的语法规则,因为Stata方括号里需要的是整数行号,而布尔表达式无法直接被解析为行号。不过有几种简单的方法可以解决这个问题:
方法1:先将目标值存入标量再替换
因为你提到cumul的取值是唯一的,所以cumul==20只会对应一行数据,我们可以先把该行的country值存入一个标量,再用这个标量替换第12行的值:
// 提取cumul==20对应的country值存入标量 scalar target_country = country if cumul==20 // 替换第12行的country变量 replace country = target_country in 12
方法2:先获取目标行号再用行号索引
先通过条件定位到目标行的行号,存入本地宏,再用宏来做行索引:
// 获取cumul==20对应的行号,存入本地宏target_row local target_row = _n if cumul==20 // 用行号索引替换第12行的country变量 replace country = country[`target_row'] in 12
补充说明
如果cumul可能存在多个等于20的行(虽然你说它是唯一值),可以用levelsof命令配合处理来指定取某一行的值,比如取匹配到的第一行:
levelsof _n if cumul==20, local(target_rows) local target_row = word("`target_rows'", 1) replace country = country[`target_row'] in 12
内容的提问来源于stack exchange,提问作者Euan Ritchie
相关产品推荐
相关产品推荐

