How to get the difference of two variables, when there are missing values?

こ雲淡風輕ζ 提交于 2019-12-12 03:49:47

问题


I have two variables A & B, and I want to get A - B for a new variable called C. For that I used generate C = A - B. But it gives some missing values in C, when either A or B contains missing values.

For example, if A is 5000 while B is missing, it gives missing for C, even though I want C as 5000.

So I want to consider those missing values as zeros & get the answer. How can I do it in Stata?


回答1:


 gen C = cond(missing(A, B), min(A, B), A - B) 

which is short-hand for

 gen C = A - B 
 replace C = min(A, B) if missing(A, B) 

which is short for

 gen C = A - B 
 replace C = B if missing(A) 
 replace C = A if missing(B) 

For a tutorial on cond() see http://www.stata-journal.com/article.html?article=pr0016

The result of min(A, B) is always the single non-missing value when there is one. (Also, true of max(A, B) in fact.)

You didn't spell out what you want if both are missing; the code here returns missing as the difference.

If your missings really are to be thought of as zeros, see help mvencode.



来源:https://stackoverflow.com/questions/14795283/how-to-get-the-difference-of-two-variables-when-there-are-missing-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!