st: Cumulative frequency in reverse order [was:RE: RE: statalist-digest V4 #1269]

 From "Nick Cox" To Subject st: Cumulative frequency in reverse order [was:RE: RE: statalist-digest V4 #1269] Date Thu, 5 Jun 2003 09:53:14 +0100

```Subhash Pokhrel

> Can anyone in the list help me solve the following simple problem?
>
> I want to get the cummulative frequency in the reverse
> order. Usually, when
> you tabulate, Stata gives you a cummulative frequency
> starting from the
> lowest value (if X=0,1,....25; the cf becomes 100% at
> x=25). What I want is
> my cf getting 100% at x=0.

This can be tackled by a variation on the approach outlined
in

How do I tabulate cumulative frequencies?
http://www.stata.com/support/faqs/data/tabdisp.html

Note that

. search cumulative

or

. search cumulative frequencies

would have pointed to this FAQ.

program subhash, sortpreserve
version 8
syntax varname(numeric) [if] [in]
marksample touse
tempvar reverse freq cumfreq
qui gen `reverse' = -`varlist'
bysort `touse' `reverse': gen long `freq' = _N
by `touse' `reverse' : gen long `cumfreq' = _N * (_n == 1)
qui by `touse' : replace `cumfreq' = sum(`cumfreq')
qui replace `cumfreq' = 100 * `cumfreq' / `cumfreq'[_N]
label var `freq' "Frequency"
label var `cumfreq' "Cumulative percent"
format `cumfreq' %6.2f
tabdisp `varlist' if `touse', c(`freq' `cumfreq')
end

(back translation to 7: not tested)
program def subhash7, sortpreserve
version 7
syntax varname(numeric) [if] [in]
marksample touse
tempvar reverse freq cumfreq
qui gen `reverse' = -`varlist'
bysort `touse' `reverse': gen long `freq' = _N
by `touse' `reverse' : gen long `cumfreq' = _N * (_n == 1)
qui by `touse' : replace `cumfreq' = sum(`cumfreq')
qui replace `cumfreq' = 100 * `cumfreq' / `cumfreq'[_N]
label var `freq' "Frequency"
label var `cumfreq' "Cumulative percent"
format `cumfreq' %6.2f
tabdisp `varlist' if `touse', c(`freq' `cumfreq')
end

e.g. subhash myvar

Nick
n.j.cox@durham.ac.uk

*
*   For searches and help try:
*   http://www.stata.com/support/faqs/res/findit.html
*   http://www.stata.com/support/statalist/faq
*   http://www.ats.ucla.edu/stat/stata/
```