How to get the difference of two variables, when t

2019-09-06 16:04发布

问题:

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.



标签: stata