创建变量以分组缺少值的数据点

问题描述 投票:-3回答:1

[我正在尝试在Stata中使用generate命令创建一个名为complete的二进制变量,如果没有缺失值,则该变量的值为1。

这是我的伪代码:

generate complete = 1 if no missing values

我可以使用什么命令/条件?

statistics stata analysis
1个回答
0
投票

正如尼克已经建议测试一个变量(在此示例中为foo)中的缺失值时,执行此操作的最佳方法是:

generate complete = !missing(foo)

如果要测试两个或多个变量(在此示例中为foobar)中缺少的值,则需要使用egen(如Nick所建议的),这是您的操作方法。创建二进制incomplete更容易,但是如果需要的话,代码的最后一行显示了如何创建与complete相反的incomplete

* Counts number of missing values
egen incomplete = rowmiss(foo bar)
* Turn missing count into binary 
replace incomplete = 1 if incomplete > 1
* If needed, create an inverse of the binary to get complete as OP asked for
recode incomplete (1=0) (0=1), generate(complete) 

最后,您可以对数据集中的所有变量执行以下操作:

* Creates a list of all variables and store them in r(varlist)
ds
* Counts number of missing values
egen incomplete = rowmiss(`r(varlist)')
* Turn missing count into binary 
replace incomplete = 1 if incomplete > 1
* If needed, create an inverse of the binary to get complete as OP asked for
recode incomplete (1=0) (0=1), generate(complete) 

这里是一个示例数据集和您可以使用的代码!

clear
input int(foo bar foo2) str5 foostr
123 123 123 "alpha"
123   . 123 "beta" 
  .   . 123 ""     
123 123   . "delta"
end

* one variable
generate complete1 = !missing(foo)

* Two or more variables
egen    incomplete2 = rowmiss(foo bar)
replace incomplete2 = 1 if incomplete2 > 1
recode  incomplete2 (1=0) (0=1), generate(complete2) 

*All variables
ds
egen    incomplete3 = rowmiss(`r(varlist)')
replace incomplete3 = 1 if incomplete3 > 1
recode  incomplete3 (1=0) (0=1), generate(complete3) 

祝您好运,不要介意stackoverflow上的家伙,他们对他们认为简单的问题感到恼火,并且由于某种原因感到他们仍然必须回答它。

© www.soinside.com 2019 - 2024. All rights reserved.