我有一个数据集,每个人(行)都有值0
,1
或者.
有许多变量(列)。
我想创建两个变量。一个包含所有的计数,一个包含每个人(行)0
的所有计数1
。就我而言,变量名称中没有模式。由于这个原因,我创建了一个所有现有变量的变量列表,除了不需要计数的变量之外。
+--------+--------+------+------+------+------+------+----------+--------+
| 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(),但是由于我的数据集很大(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')
怎么样
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
显然是语法错误。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句