【发布时间】:2015-08-15 23:45:39
【问题描述】:
我有一个数据集,其中每个人(行)在多个变量(列)中都有值 0、1 或 .。
我想创建两个变量。一个包含所有0 的计数,另一个包含每个人(行)的所有1 的计数。
就我而言,变量名中没有模式。出于这个原因,我创建了一个包含所有现有变量的 varlist,不包括不需要计算的变量。
+--------+--------+------+------+------+------+------+----------+--------+
| ID | region | Qa | Qb | C3 | C4 | Wa | count 0 | count 1|
+--------+--------+------+------+------+------+------+----------+--------+
| 1 | A | 1 | 1 | 1 | 1 | . | 0 | 4 |
| 2 | B | 0 | 0 | 0 | 1 | 1 | 3 | 2 |
| 3 | C | 0 | 0 | . | 0 | 0 | 4 | 0 |
| 4 | D | 1 | 1 | 1 | 1 | 0 | 0 | 4 |
+--------+--------+------+------+------+------+------+----------+--------+
以下工作,但是,我不能添加 if 语句
ds ID region, not // all variables in the dataset apart from ID region
return list
local varlist = r(varlist)
egen count_of_1s = rowtotal(`varlist')
如果我将最后一行更改为下面的行,我会收到无效语法错误。
egen count_of_1s = rowtotal(`varlist') if `v' == 1
我从计数转向求和,因为我认为这是解决问题的一种偷偷摸摸的方法。我可以将值从 0,1 更改为 1, 2,然后在两个不同的变量中分别对所有两个值求和,然后进行相应除以得到每行 1 或 2 的实际计数。
我发现了这个Stata: Using egen, anycount() when values vary for each observation,但是由于我的数据集非常大(100.000 行和 3000 列),Stata 冻结了。
任何帮助将不胜感激:-)
基于威廉回应的解决方案
* number of total valid responses (0s and 1s, excluding . )
ds ID region, not // all variables in the dataset apart from ID region
return list
local varlist = r(varlist)
egen count_of_nonmiss = rownonmiss(`varlist') // this counts all the 0s and 1s (namely, the non missing values)
* total numbers of 1s per row
ds ID region count_of_nonmiss, not // CAUTION: count_of_nonmiss needs not to be taken into account for this!
return list
local varlist = r(varlist)
generate count_of_1s = rowtotal(`varlist')
【问题讨论】: