寻找观察

时间:2019-05-17 10:59:50

标签: stata

我在Stata中有以下数据:

paint

如何找到第一个1的观测值小于或等于23paint == 1的观测值?

例如:

1 7 14 时:

paint == 2

1 2 3 7 8 9 14 15 时:

paint == 3

1 2 3 4 5 7 8 9 10 14 15 16 17 18 时:

Class App\Http\Controllers\AdminNewsController does not exist

我还想将每组结果存储在本地宏中。

1 个答案:

答案 0 :(得分:2)

以下对我有用:

generate obs = _n
bysort id (year): generate tag = (paint == 2) // CHANGE THIS NUMBER
bysort id (year): list if sum(tag) <= 1 & sum(tag[_n-1]) == 0

当变量的paint值为2时,这将显示所有观察结果:

---------------------------------------------------------------------------------------------
-> id = 1000789

     +------------------------------------+
     |      id   year   paint   obs   tag |
     |------------------------------------|
  1. | 1000789   2012       1     1     0 |
  2. | 1000789   2013       1     2     0 |
  3. | 1000789   2014       2     3     1 |
     +------------------------------------+


---------------------------------------------------------------------------------------------
-> id = 1000790

     +------------------------------------+
     |      id   year   paint   obs   tag |
     |------------------------------------|
  1. | 1000790   2012       1     7     0 |
  2. | 1000790   2013       1     8     0 |
  3. | 1000790   2014       2     9     1 |
     +------------------------------------+


---------------------------------------------------------------------------------------------
-> id = 1000791

     +------------------------------------+
     |      id   year   paint   obs   tag |
     |------------------------------------|
  1. | 1000791   2012       1    14     0 |
  2. | 1000791   2013       2    15     1 |
     +------------------------------------+

要将其中的每个集合保存在本地宏中,您可以执行以下操作:

forvalues i = 1 / 3 {
    preserve
    generate obs = _n
    bysort id (year): generate tag = (paint == `i')
    bysort id (year): keep if sum(tag) <= 1 & sum(tag[_n-1]) == 0
    quietly levelsof obs, local(obs`i')
    restore
}

. display "`obs1'"
1 7 14

. display "`obs2'"
1 2 3 7 8 9 14 15

. display "`obs3'"
1 2 3 4 5 7 8 9 10 14 15 16 17 18