在 Stata 中获取两个变量的总和,包括缺失值。

huangapple go评论153阅读模式
英文:

Getting the sum of two variables on Stata with missing values

问题

如何生成一个新变量,该变量给出两个变量(msf_n_4weeksmsm_n_4weeks)的总和,但只在这两个变量的值都缺失时赋予缺失值。这两个变量既有缺失值,又有0值。我使用了下面的代码,但它不仅将总和为0的情况分配了值0,还将两个变量都缺失的情况分配了值0

egen m_n_4weeks = rowtotal(msf_n_4weeks msm_n_4weeks)

相反,我想要得到类似这样的结果:

msf_n_4weeks  msm_n_4weeks  m_n_4weeks
5             3             8
0             2             2
12            0             12
6             .             6
.             5             5
.             .             .

我该如何做到这一点?

英文:

How do I generate a new variable which gives me the sum of two variables (msf_n_4weeks and msm_n_4weeks) but only assigns a missing value if BOTH of the values for the variables is missing. The variables have missing values and also 0 as a value. I used the below code and it assigned the value 0 to those where the sum is 0 but also to those where both variables have missing values.

egen m_n_4weeks = rowtotal(msf_n_4weeks msm_n_4weeks)

Instead, I want to get something like this:

msf_n_4weeks  msm_n_4weeks  m_n_4weeks
5             3             8                  
0             2             2                     
12            0             12                    
6             .             6                
.             5             5                
.             .             .     

How can I do this?

答案1

得分: 2

你的尝试非常接近解决方案:请查看egen中的rowtotal(),在帮助文档的文件中。然后使用以下代码:
egen m_n_4weeks = rowtotal(msf_n_4weeks msm_n_4weeks), missing

英文:

Your attempt is very close to the solution: see rowtotal() in the egen help file.

egen m_n_4weeks = rowtotal(msf_n_4weeks msm_n_4weeks), missing

答案2

得分: 0

清除 
输入 msf_n_4weeks  msm_n_4weeks  m_n_4weeks
5             3             8                  
0             2             2                     
12            0             12                    
6             .             6                
.             5             5                
.             .             .     
结束 

本地变量 a msf_n_4weeks 
本地变量 b msm_n_4weeks 
生成 wanted = 条件(缺失(`a`) & 缺失(`b`), . , 条件(缺失(`b`), 0, `b`) + 条件(缺失(`a`), 0, `a`)) 

另一种方法是这样做。
英文:
clear 
input msf_n_4weeks  msm_n_4weeks  m_n_4weeks
5             3             8                  
0             2             2                     
12            0             12                    
6             .             6                
.             5             5                
.             .             .     
end 

local a msf_n_4weeks 
local b msm_n_4weeks 
gen wanted = cond(missing(`a') & missing(`b'), . , cond(missing(`b'), 0, `b') + cond(missing(`a'), 0, `a')) 


is another way to do it.

huangapple
  • 本文由 发表于 2023年6月8日 01:23:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/76425725.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定