Stata 中的按行计数/值总和

问题描述 投票:0回答:3

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

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:当每个观察值不同时使用 egen、anycount() 但是 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')
row stata
3个回答
4
投票

怎么样

egen count_of_nonmiss = rownonmiss(`varlist')
generate count_of_0s = count_of_nonmiss - count_of_1s

当宏

varlist
的值替换为
if
子句时,该命令将扩展为

egen count_of_1s = rowtotal(`varlist') if Qa Qb C3 C4 Wa == 1

显然是语法错误。


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)

0
投票

我遇到了同样的问题,我使用了这段代码egen count2 = anycount(x1-x3), value(0)与Gustavo。

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