Notice: On April 23, 2014, Statalist moved from an email list to a forum, based at statalist.org.
From | Friedrich Huebler <fhuebler@gmail.com> |
To | statalist@hsphsun2.harvard.edu |
Subject | st: Row totals: looking for more efficient solution |
Date | Sun, 23 May 2010 14:51:23 -0400 |
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 Thanks, Friedrich * * 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/