【问题标题】:Counting occurrences of values of string variable using collapse使用折叠计算字符串变量值的出现次数
【发布时间】:2017-12-03 12:16:26
【问题描述】:

在像下面这样的数据集中,

clear
input patid str2 dx 
1   qw
1   qe
1   qw
2   qw
2   qw
2   qs
2   qs
3   qe
3   qe
3   qs
3   qw
3   qw
3   qw
3   qs
4   qe
5   qa
5   qs
5   qw
5   qe
5   qw
end

我发现我可以使用下标 [1] 计算字符串变量 dx 的每个值的出现次数,或者如果使用 collapse[2] 将 dx 转换为数字标签。

在使用collapse 时,是否有一个命令或语法可以让我直接从字符串变量本身计算出现次数(无需转换等)?

例如如果我尝试了collapse (count) countdx=dx, by(patid dx),这将返回错误消息variable dx not found

(当然,这不应该工作:当我尝试collapse (count) countdx=dx, by(patid)时,这会返回错误type mismatch

注意事项:

[1]

by patid dx, sort: egen ndx = count(dx)
by patid dx: g orderdx=_n
by patid dx: drop if orderdx>1

[2]

g numdx=.
replace numdx=1 if dx=="qa"
replace numdx=2 if dx=="qe"
replace numdx=3 if dx=="qs"
replace numdx=4 if dx=="qw"
collapse (count)  countdx=numdx, by(patid dx)

【问题讨论】:

    标签: string count stata collapse


    【解决方案1】:

    您的示例,但不是您的问题,都暗示您希望分别计算标识符patid 的每个不同值。

    clear
    input patid str2 dx 
    1   qw
    1   qe
    1   qw
    2   qw
    2   qw
    2   qs
    2   qs
    3   qe
    3   qe
    3   qs
    3   qw
    3   qw
    3   qw
    3   qs
    4   qe
    5   qa
    5   qs
    5   qw
    5   qe
    5   qw
    end
    
    bysort patid dx : gen count = _N 
    
    tabdisp patid dx , c(count) 
    
    ----------------------------------
              |           dx          
        patid |   qa    qe    qs    qw
    ----------+-----------------------
            1 |          1           2
            2 |                2     2
            3 |          2     2     3
            4 |          1            
            5 |    1     1     1     2
    ----------------------------------
    

    有关该领域技术的评论,请参阅this paper。在Statalist 中搜索dm0042 的提及会发现很多相关示例。

    对于中等大小的问题,tabdisp 不会特别实用。这里提到是为了直接显示上一个命令的作用。

    将此扩展到collapse,一个简单的设备是

    gen one = 1
    
    collapse (sum) one, by(patid dx)
    

    尽管我应该提到contract 是为此目的而更明确地编写的(参见 Cox 1998 中对其前身的讨论)。

    另一方面,如果您确实创建了 count 变量,那么

    collapse (mean) count, by(patid dx) 
    

    会产生完全相同的效果。

    Cox, N.J. 1998。将数据集折叠为频率。 Stata 技术公告 44:2-3。 .pdf here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-24
      相关资源
      最近更新 更多