Return 来自不同命令的矩阵

Return a matrix from distinct command

我有一个关于 Stata 中的 distinct 命令的简单问题。

使用by前缀时,可以return是r(N)的一维矩阵吗?

例如:

sysuse auto,clear
bysort foreign: distinct rep78

我可以存储一个 [2,1] 矩阵,每一行代表 rep78 个不同的 个值吗?

手册上好像说只按值存储最后一个不同值的个数。

您可以轻松地为此创建自己的包装器:

sysuse auto,clear

sort foreign                
levelsof foreign, local(foreign_levels)
local number_of_foreign_levels : word count `foreign_levels'

matrix distinct_mat = J(`number_of_foreign_levels', 1, 0)

forvalues i = 1 / `number_of_foreign_levels' {
     quietly distinct rep78 if foreign == `i' - 1
     matrix distinct_mat[`i', 1] = r(ndistinct)
}

matrix list distinct_mat

distinct_mat[2,1]
    c1
r1   5
r2   3

请注意,不同观察值的数量存储在 r(ndistinct) 中,而不是 r(N)

这是另一种将不同值的数量放入矩阵的方法。

. sysuse auto
(1978 Automobile Data)

. egen tag = tag(foreign rep78)

. tab foreign if tag, matcell(foo)

   Car type |      Freq.     Percent        Cum.
------------+-----------------------------------
   Domestic |          5       62.50       62.50
    Foreign |          3       37.50      100.00
------------+-----------------------------------
      Total |          8      100.00