0

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

当使用by前缀时,它可以返回一个一维矩阵r(N)吗?

例如:

sysuse auto,clear
bysort foreign: distinct rep78

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

该手册似乎建议它仅按值存储最后一个不同值的数量。

4

2 回答 2

4

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

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)中。

于 2018-06-04T14:15:16.353 回答
2

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

. 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
于 2018-06-04T15:09:43.070 回答