|
rangestat 命令帮助里面例子
Median investment of other firms in a given year
Some problems are hard to solve in Stata without a loop. You can easily calculate the median
investment from all firms in any given year using a single egen call:
--------------------------- example do-file content ---------------------------
webuse grunfeld, clear
bysort year: egen m = median(invest)
--------------------------------------------------------------------------------
(click to run)
but there is no equally easy way to get an observation-specific median calculated using all
observations within the group except the one from the current observation. A naive brute force
solution is to loop over observations:
--------------------------- example do-file content ---------------------------
webuse grunfeld, clear
gen double mexclude = .
quietly forvalues i=1/`=_N' {
sum invest if year == year[`i'] & company != company[`i'], detail
replace mexclude = r(p50) in `i'
}
list in 10/20
--------------------------------------------------------------------------------
(click to run)
However, this is much slower than the egen direct solution and will become painfully slow as the
number of observations increases.
With rangestat, all you need is
--------------------------- example do-file content ---------------------------
webuse grunfeld, clear
rangestat (median) invest, interval(year 0 0) excludeself
list in 10/20
--------------------------------------------------------------------------------
(click to run)
Note that the rangestat interval can be degenerate, as is the case above. Setting both low and high to
zero will have the effect of selecting, for the current observation, all (and only) observations that
have the same year. As the excludeself option is specified, the value of the variable invest for each
current observation will be ignored.
|