寻找第二个最小值

时间:2018-07-03 12:59:41

标签: stata

对于每个观察,我想获取变量的最后五个观察中的第二个最小值。

您知道我必须使用哪个命令吗?

* Example generated by -dataex-. To install: ssc install dataex 
clear 
input str5 var1 str26 var2 
"Value" "2nd smallest of previous 5" 
"8" "" 
"0" "" 
"4" "" 
"5" "" 
"0" "" 
"6" "0" 
"8" "0" 
"10" "4" 
"8" "5" 
"8" "6" 
end 

2 个答案:

答案 0 :(得分:2)

我认为这就是您想要的:

sysuse auto, clear

egen rank = rank(mpg) if _n > `= _N - 5', unique
egen low = total(mpg / (rank == 2)) if _n > `= _N - 5'

list mpg rank low if _n > `= _N - 5'

     +------------------+
     | mpg   rank   low |
     |------------------|
 70. |  23      2    23 |
 71. |  41      5    23 |
 72. |  25      4    23 |
 73. |  25      3    23 |
 74. |  17      1    23 |
     +------------------+

答案 1 :(得分:2)

原始问题:最近5个中的第2个

另一种方法是将5中的倒数第二低作为较低的四分位数:

. sysuse auto, clear
(1978 Automobile Data)

. quietly su mpg in -5/L , detail

. di r(p25)
23

修订后的问题:前5个中的第2个

* Example generated by -dataex-. To install: ssc install dataex 
clear 
input data min2f5 
8 . 
0 . 
4 . 
5 . 
0 . 
6 0 
8 0 
10 4 
8 5 
8 6 
end 

mata:  
    mata clear

    real second(real colvector X) {
        if (rows(X) < 5) return(.) 
        X = sort(X, 1)    
        return(X[2])
    }

end 

gen long id = _n 
* install just once 
ssc inst rangestat 
rangestat (second) data, interval(id -5 -1)

list 

     +------------------------------+
     | data   min2f5   id   second1 |
     |------------------------------|
  1. |    8        .    1         . |
  2. |    0        .    2         . |
  3. |    4        .    3         . |
  4. |    5        .    4         . |
  5. |    0        .    5         . |
     |------------------------------|
  6. |    6        0    6         0 |
  7. |    8        0    7         0 |
  8. |   10        4    8         4 |
  9. |    8        5    9         5 |
 10. |    8        6   10         6 |
     +------------------------------+