Finding the second smallest value

微笑、不失礼 提交于 2019-12-25 02:24:12

问题


For every observation, I want to get the second smallest value of the last five observations of a variable.

Do you know which command I have to use?

* 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 

回答1:


Original problem: 2nd of last 5

Another way to do it is that the 2nd lowest out of 5 will be returned as the lower quartile:

. sysuse auto, clear
(1978 Automobile Data)

. quietly su mpg in -5/L , detail

. di r(p25)
23

Revised problem: 2nd of previous 5

* 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 |
     +------------------------------+



回答2:


I think this is what you are looking for:

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 |
     +------------------+


来源:https://stackoverflow.com/questions/51155287/finding-the-second-smallest-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!