Notice: On March 31, it was announced that Statalist is moving from an email list to a forum. The old list will shut down on April 23, and its replacement, statalist.org is already up and running.

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

 From "Nick Cox" To Subject st: RE: Row totals: looking for more efficient solution Date Sun, 23 May 2010 19:59:47 +0100

gen pop = 0

forval j = 5/7 {
replace pop = pop + pop`j' if inrange(`j', start, end)
}

???

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

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/