【发布时间】: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