2016-10-24 84 views
-2

我正在处理超过200,000行的数据集。我想根据特定条件用下一行或前一行中的值替换缺失的值。下面的循环只运行一次,但只要缺少指定变量的值,我希望它继续运行。数据如下所示:Stata foreach循环替换缺失值

ID primary_ins primary_ins_collegecodebranch 
36 GROSSMONT COLLEGE 120800 
37 GROSSMONT COLLEGE 120800 
38 GROSSMONT COLLEGE 120800 
39 SAN DIEGO STATE UNIVERSITY 
40 SAN DIEGO STATE UNIVERSITY    
41 SAN DIEGO STATE UNIVERSITY 115100 
42 DIEGO STATE UNIVERSITY 115100 
43 GROSSMONT COLLEGE 120800 
44 GROSSMONT COLLEGE 120800 
45 FRESNO CITY COLLEGE 130700 



gen primary_ins_collegecodebranch=collegecodebranch if primary_ins==college 
    foreach x of varlist primary_ins_collegecodebranch{ 
     replace primary_ins_collegecodebranch=primary_ins_collegecodebranch[_n+1] if missing(primary_ins_collegecodebranch) & primary_ins==primary_ins[_n+1] 
     replace primary_ins_collegecodebranch=primary_ins_collegecodebranch[_n-1] if missing(primary_ins_collegecodebranch) & primary_ins==primary_ins[_n-1] 
    } 

回答

1

这是相当不清楚的。例如,你不能在简单的层面上解释数据的基本结构(学生课程等)。标识符是什么意思?他们是否信息丰富?看起来你的数据片段中存在一些错误,但它并不明确变量是字符串还是数字。所以,这个例子并不是https://stackoverflow.com/help/mcve

foreach循环只是一个循环,只有一个变量,它将被执行一次。在这种情况下,它是多余的,特别是因为循环不包括其本地宏x

这里有很多很长的变量名称,无疑有很好的理由,但是它们让其他人难以遵循这一点。

使用本地宏定义,我将更简单地显示结构。

local z primary_ins_collegecodebranch 
local y collegecodebranch 
gen `z' = `y' if primary_ins==college 
replace `z' = `z'[_n+1] if missing(`z') & primary_ins==primary_ins[_n+1] 
replace `z'= `z'[_n-1] if missing(`z') & primary_ins==primary_ins[_n-1] 

正如你所说的,但用在Stata使用的术语,问题是相邻值的缺失值插补之一。

请参阅前面的线程replace missing value based on linear prediction of nearby cells

我不太明白您的插补规则(“基于特定条件”是完全模糊的),但我敢打赌那是无需环路。检查出mipolate(SSC)。你可能会追求它所谓的分组插值,但是需要识别组。

请参阅http://www.stata.com/support/faqs/data-management/replacing-missing-values/解释为什么您的两个replace语句不对称工作。

编辑也许你只是想

如果primary_ins_collegecodebranch是字符串

local z primary_ins_collegecodebranch 
bysort primary_ins (`z') : replace `z' = `z'[_N] if missing(`z') 

如果primary_ins_collegecodebranch是数字

local z primary_ins_collegecodebranch 
bysort primary_ins (`z') : replace `z' = `z'[1] if missing(`z') 

这是mipolate(SSC)的意义上的GroupWise插,除了mipolate不适用于字符串,这就是为什么第一个代码块可能是相关的。