为什么制表或汇总在程序内部实现时不考虑缺失值?

Why do tabulate or summarize not take into account missing values when implemented inside a program?

举个例子,假设这是您的数据集:

cat sex age
1   1   13
1   0   14
1   1   .
2   1   23
2   1   45
2   1   15

如果您想在 catsex 之间创建 table 个频率,您 tabulate 这两个变量将得到以下结果:

tab cat sex
       |         sex
   cat |         0          1 |     Total
-----------+----------------------+----------
     1 |         1          2 |         3 
     2 |         0          3 |         3 
-----------+----------------------+----------
 Total |         1          5 |         6 

我正在编写一个涉及三个变量的 Stata 程序,即 catsexage。获取前两个变量的频率矩阵只是我需要进一步计算的中间步骤。

cap program drop myexample
program def myexample, rclass byable(recall) sortpreserve
version 14
syntax varlist [aweight iweight fweight] [if] [in] [ , AGgregate  ]
args var1 var2 var3
tempname F

marksample touse 
set more off

if "`aggregate'" == "" {
    local var1:  word 1 of `varlist'
    local var2: word 2 of `varlist'
    local var3:  word 3 of `varlist'

    qui: tab `var1' `var2' [`weight' `exp'] if `touse', matcell(`F')  label matcol(`var2')

    mat list `F'
}
   end

然而,当我运行:

myexample cat sex age

我得到的结果与我的预期不同:

__000001[2,2]
     c1  c2
r1   1   1
r2   0   3

即假设age包含缺失值,即使不直接参与制表,程序也会忽略缺失值,不考虑那个观察值。我需要得到第一次制表的结果。我尝试使用 summarize 代替,但出现了同样的问题。在程序内部实现时,不计算缺失值。

如果我明白你想要选项卡包含缺失值?如果是这样,你只需要要求它

tab myvar1 myvar2, mi

来自文档

missing : treat missing values like other values

这是marksample造成的。 help mark 中的规则 5 指出

The marker variable is set to 0 in observations for which any of the numeric variables in varlist contain a numeric missing value.

您应该使用 novarlist 选项。根据帮助文件,

novarlist is for use with marksample. It specifies that missing values among variables in varlist not cause the marker variable to be set to 0.

您在抱怨您在自己的程序中内置的行为。责任和解释在你手中。

效果

marksample touse 

然后调用带有限定符

的命令
if `touse' 

就是忽略缺失值。 marksample 默认标记为 "to use" 那些指定的所有变量都具有非缺失值的观察;其他意见被标记为被忽略。它还考虑了任何 ifin 限定符和任何零权重。

正如@Noobie 所解释的那样,在任何情况下,tabulate 都默认从表格中省略缺失值。

因此,要获得您想要的结果,您需要将 marksample 调用修改为

marksample touse, novarlist 

并使用 missing 选项调用 tabulate(如果它是强制性的)或允许用户指定 missing 选项,然后将其传递给 tabulate .

你也问summarize。按照设计,该命令会忽略缺失值。我不知道您希望 summarize 对它们做什么。它可以报告缺失值的计数。如果您需要,可以使用其他几个命令,例如 codebookmissings (Stata Journal)。您始终可以在程序中包含有关缺失的报告,例如使用 count 计算缺失并使用 display 结果。

我知道你的程序还有很多工作正在进行中,所以不会对你不问的细节发表评论。