在 Stata 中获取分类变量的级别数作为单个数字

Get the number of levels of a categorical variable as a single number in Stata

我正在尝试找到一种方法来将分类变量的级别数作为单个数字获取。例如,如果我有一个具有 4 个级别的变量 X,我需要以某种方式获得该数字。如果我输入 levelsof X 我会得到以下 1 2 3 4 但我不能从那里只得到数字 4。有没有办法使用 levelsof 或其他命令来做到这一点?

对于任何类型的变量,各种命令都会为您提供不同值的数量。 ("Categorical variable" 是一个统计概念,而不是 Stata 概念。)为了一次性的目的,也许最简单的方法是使用 tabulate 请求单向制表。不同值的数量就是 table 中的行数,返回为 r(r)。请注意 (1) 您可以抑制 table 本身(这在程序或 do 文件中很有用)和 (2) 默认情况下排除缺失值:

. sysuse auto, clear
(1978 Automobile Data)

. qui tab foreign

. ret li

scalars:
                  r(N) =  74
                  r(r) =  2

. qui tab rep78

. ret li

scalars:
                  r(N) =  69
                  r(r) =  5

. qui tab rep78, missing

. ret li

scalars:
                  r(N) =  74
                  r(r) =  6

对这个问题的更广泛的评论已经发布 here。那篇论文介绍了一个 distinct 命令。它的用途包括直接支持系统地查看不同值的数量。 search distinct 在 Stata 中查找最新版本的下载源。

. distinct

              |           Observations
              |         total      distinct
--------------+----------------------------
         make |            74            74
        price |            74            74
          mpg |            74            21
        rep78 |            69             5
     headroom |            74             8
        trunk |            74            18
       weight |            74            64
       length |            74            47
         turn |            74            18
 displacement |            74            31
   gear_ratio |            74            36
      foreign |            74             2

你可以在levelsof之后看r(r):

. sysuse auto
(1978 Automobile Data)

. levelsof rep78
1 2 3 4 5

. display "rep78 has " `r(r)' " levels."
rep78 has 5 levels.