Bookmark and Share

Notice: On April 23, 2014, Statalist moved from an email list to a forum, based at statalist.org.


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: st: RE: Row totals: looking for more efficient solution


From   Friedrich Huebler <[email protected]>
To   [email protected]
Subject   Re: st: RE: Row totals: looking for more efficient solution
Date   Sun, 23 May 2010 16:06:20 -0400

Brilliant! Thank you, Nick.

Friedrich

On Sun, May 23, 2010 at 2:59 PM, Nick Cox <[email protected]> wrote:
> gen pop = 0
>
> forval j = 5/7 {
>        replace pop = pop + pop`j' if inrange(`j', start, end)
> }
>
> ???
>
> Nick
> [email protected]
>
> Friedrich Huebler
>
> I work with population data and have to create the total population
> for different age groups. The data are similar to the example below.
>
> clear all
> input start end pop5 pop6 pop7
> 5 6 12 11 10
> 5 7 12 11 10
> 6 7 12 11 10
> end
>
> "pop5" is the population 5 years of age, "pop6" the population 6 years
> of age, and so on. My goal is to create a variable "pop" with the sum
> of the population in the age groups indicated by the "start" and "end"
> variables. The result should look like this:
>
> start  end  pop5  pop6  pop7  pop
>    5    6    12    11    10   23
>    5    7    12    11    10   33
>    6    7    12    11    10   21
>
> The commands below deliver the result I need but there must be a more
> efficient way to do this. The loop over all observations in the data
> is especially time consuming.
>
> foreach var of varlist pop5 - pop7 {
>  gen `var'copy = `var'
> }
> count
> forval i = 1/`r(N)' {
>  forval j = 5/7 {
>    if `j' < start[`i'] | `j' > end[`i'] {
>      replace pop`j'copy = . in `i'
>    }
>  }
> }
> egen pop = rowtotal(pop5copy - pop7copy)
> drop pop5copy - pop7copy

*
*   For searches and help try:
*   http://www.stata.com/help.cgi?search
*   http://www.stata.com/support/statalist/faq
*   http://www.ats.ucla.edu/stat/stata/


© Copyright 1996–2018 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   Site index