如何解决Stata对`count`命令使用`by`选项的限制?

时间:2013-05-29 21:34:08

标签: sorting count stata

我需要计算各州高中教育的百分比。但Stata函数count不允许by选项。到目前为止,我有以下内容:

count
local totalPopulation = r(N )

count if schenr==0
local eduBelowHighSchool = r(N)
local _eduBelowHighSchool=`eduBelowHighSchool'/`totalPopulation'

count if schenr==1
local eduHighSchool = r(N )
local _eduHighSchool=`eduHighSchool'/`totalPopulation'

count if schenr==2
local eduCollege = r(N )
local _eduCollege=`eduCollege'/`totalPopulation'

gen eduBelowHighSchool =`_eduBelowHighSchool'
gen eduHighSchool =`_eduHighSchool'
gen eduCollege =`_eduCollege'

//如何计算每个州的个别值?我不能使用count, by (state),我可以吗?以上代码生成下表:

enter image description here

还有其他方法可以解决这个问题吗?

1 个答案:

答案 0 :(得分:4)

count是Stata命令,而不是函数。在Stata中,“功能”不是“命令”的另一个术语;相反,命令和功能是分开的。

在你的例子中,schenr在高中时显然为1,在没有时为0。因此,您想要的百分比只是schenr的平均值(乘以100)。

如果你想要一个新变量,

egen pc_highschool = mean(100 * schenr), by(state) 

将在其适用的每个观察中使用相同的百分比。要获得每个州的列表一次,

egen tag = tag(state)
l state pc_highschool if tag 

是一种方法。

但您可以使用tabulatetabletabstat获取表格,而无需创建新变量。考虑这个可重复的例子:

. sysuse auto 

. tabulate rep78, su(foreign) nost

        Repair |   Summary of Car type
   Record 1978 |        Mean       Freq.
   ------------+------------------------
             1 |           0           2
             2 |           0           8
             3 |          .1          30
             4 |          .5          18
             5 |   .81818182          11
   ------------+------------------------
         Total |   .30434783          69

. gen foreign2 = 100 * foreign

. tabulate rep78, su(foreign2) nost

        Repair |   Summary of foreign2
   Record 1978 |        Mean       Freq.
   ------------+------------------------
             1 |           0           2
             2 |           0           8
             3 |          10          30
             4 |          50          18
             5 |   81.818182          11
   ------------+------------------------
         Total |   30.434783          69

如果您想要新数据集,请使用contract。 (将答案与您最近提出的问题How to retrieve data from multiple Stata files?进行比较。)