检查组内数据是否恒定

Check that data are constant within group

我经常发现自己需要检查变量在组内是否为常量。这就是我目前的处理方式(假设该组由 a-b-c 定义,所讨论的变量是 var):

bys a b c (var): gen isconstant=var[1]==var[_N]
*manually inspect the results of the below tabulation; if all 1's, then it is constant
tab isconstant
drop isconstant

(请注意,上述方法假设组内没有遗漏的观察结果。如果有遗漏,我将不得不更多地考虑如何处理它。而不是手动检查,可以使用一些类似的东西assert.)

这很好用,但是有更简洁的方法吗?也许是单行解决方案,大致类似于 isid ...,但当然要检查其他内容。

您的方法背后的原理也在 this FAQ 中进行了解释,但我不知道有专门的命令。不过,它是可编程的,而你是一名程序员,那么你的呢?

这里是一个快速刺:

*! 1.0.0 NJC 2 March 2020 
program homog, sortpreserve 
    version 8 
    syntax varname [if] [in] [, MISSing BY(varlist) ] 

    * missings are ignored by default
    if "`missing'" == "" { 
        marksample touse, strok  
        if "`by'" != "" markout `touse' `by', strok 
    }
    else marksample touse, novarlist 

    tempvar OK 
    bysort `touse' `by' (`varlist') : gen byte `OK' = `varlist'[1] == `varlist'[_N] 

    quietly summarize `OK' if `touse' 

    if r(min) == 0 display as err "assertion is false" 
end 

和一些愚蠢的例子:

. sysuse auto, clear
(1978 Automobile Data)

. homog mpg
assertion is false

. homog rep78, by(rep78)

. gen one = 1

. homog one

. replace one = . in L
(1 real change made, 1 to missing)

. homog one

. homog one, missing
assertion is false

所以,原则是

  1. 没有消息就是好消息。除了错误消息之外,唯一可能的输出是一条消息 "assertion is false"。这不被视为错误。如果您不喜欢,请克隆该程序,重命名并更改其工作方式。

  2. by() 是一个选项,如果指定,则会导致所有比较都由如此确定的不同观察组进行。

  3. 默认忽略缺失。选项 missing 改变了这一点,例如 42 和 missing 被报告为不同。这也适用于任何 by() 变量的缺失值。