Stata中的逐行计数/值总和

时间:2015-08-15 23:45:40

标签: row stata

我有一个数据集,其中每个人(行)在许多变量(列)中都有值01.

我想创建两个变量。一个包含所有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,2,然后在两个不同的变量中分别对所有两个值求和,然后相应地进行除法,以获得每行1或2的实际计数。

我发现了这个 Stata: Using egen, anycount() when values vary for each observation但是Stata冻结了,因为我的数据集非常大(100.000行和3000列)。

非常感谢任何帮助: - )

基于William

的回应的解决方案
* 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')

1 个答案:

答案 0 :(得分:0)

我在计算一组变量中每个观察中指定值的出现次数时遇到了同样的问题。

我可以通过以下方式解决该问题:如果您想计算 x1-x2 值中 0 的出现次数,那么

clear
input id x1 x2 x3

        id         x1         x2         x3
1. 1  1 0 2
2. 2  2 0 2
3. 3  2 0 3
4. end
egen count2 = anycount(x1-x3), value(0)
相关问题