* Example: Calculate mean wage of people of similar age sysuse nlsw88, clear rangestat wage, interval(age -1 1) list wage_mean in 10 sum wage if inrange(age, age[10]-1, age[10]+1) assert r(mean) == wage_mean[10] rangestat mwage = wage (count) wage, interval(age -1 1) excludeself by(race industry) list mwage wage_count in 4 sum wage if inrange(age, age[4]-1, age[4]+1) & race == race[4] & industry == industry[4] & _n != 4 assert r(mean) == mwage[4] * Example: Median investment of other firms in a given year webuse grunfeld, clear bysort year: egen m = median(invest) gen double mexclude = . quietly forvalues i=1/`=_N' { sum invest if year == year[`i'] & company != company[`i'], detail replace mexclude = r(p50) in `i' } rangestat (median) invest, interval(year 0 0) excludeself assert mexclude == invest_median * Example: Looking up the education of a child's mother within a household * Example generated by -dataex-. To install: ssc install dataex clear input float(hhid personid motherid educ) 101 1 . 10 101 3 1 8 101 4 1 0 101 5 3 0 102 1 . 9 102 2 1 . 102 4 . 6 102 5 4 2 end clonevar targetid = motherid replace targetid = 0 if mi(motherid) rangestat (min) educ, interval(personid targetid targetid) by(hhid) list, sepby(hhid) * Example: Calculating correlations using a user-supplied Mata function clear all webuse grunfeld replace invest = . in 8 mata: mata set matastrict on real rowvector my_pwcorr(real matrix X) { real matrix R R = correlation(X) return(R[2,1]) } end rangestat (my_pwcorr) invest mvalue, interval(year -5 0) by(company) list my_pwcorr1 in 20 corr invest mvalue if inrange(year, year[20]-5, year[20]) & company == company[20] assert r(rho) == my_pwcorr1[20] rename my_pwcorr1 my_pwcorr1a rangestat (my_pwcorr) invest mvalue (count) invest mvalue, interval(year -5 0) by(company) casewise describe mata: mata set matastrict on real rowvector N_corr(real matrix X) { real matrix R R = correlation(X) return(rows(X), R[2,1]) } end rangestat (N_corr) invest mvalue, interval(year -5 0) by(company) casewise * Comparison with tsegen (SSC) webuse grunfeld, clear tsegen double inv_m5b = rowmean(L(0/4).invest) rangestat (mean) invest, interval(year -4 0) by(company) assert inv_m5b == invest_mean rangestat (sd) sd_inv=invest kstock (count) invest kstock, interval(year -4 0) by(company)