【问题标题】:Row-wise count/sum of values in StataStata中的逐行计数/值总和
【发布时间】:2015-08-15 23:45:39
【问题描述】:

我有一个数据集,其中每个人(行)在多个变量(列)中都有值 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 更改为 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')

【问题讨论】:

    标签: row stata


    【解决方案1】:

    怎么样

    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
    

    显然是语法错误。

    【讨论】:

    • 谢谢你。你知道我如何用varlist'? My dataset contains a large number of variables. When I run egen count_of_1s = rowtotal(varlist') 替换'if' 语句的变量名称 if `varlist' == 1 我收到一个错误,即 varlist 的第一个变量无效,我不是确定将其归因于何处。
    • 我成功了!我调整了您的解决方案并将其添加到我上面的帖子中。
    【解决方案2】:

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

    我可以通过以下方式解决该问题:如果您想计算 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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-23
      • 2013-04-18
      • 1970-01-01
      相关资源
      最近更新 更多