Notice: On April 23, 2014, Statalist moved from an email list to a forum, based at statalist.org.
From | Daniel Escher <descher@nd.edu> |
To | statalist@hsphsun2.harvard.edu |
Subject | st: Loop with capture |
Date | Wed, 24 Oct 2012 14:53:49 -0400 |
Hello, I am looking for advice about how to get my loop to capture and skip a year, not a variable. foreach v of newlist x1 x2 x3... { capture noisily: { capture confirm number `=`i'[1]' // in case that variable (e.g., unemp1972) already exists if _rc==0 { cap gen `v'1972 = (`v'1980-`v'1970)/10*2+`v'1970 cap gen `v'1976 = (`v'1980-`v'1970)/10*6+`v'1970 cap gen `v'1984 = (`v'1990-`v'1980)/10*4+`v'1980 ... } } } The problem is that x1 does not exist in 1970, but it does in 1980 and 1990. The loop as written skips the variable x1 instead of just skipping x11972 and x11976. Can I get the loop to skip just the year(s) when a variable does not exist? After reading Nick Cox's article (http://www.stata-journal.com/sjpdf.html?articlenum=pr0005 (p. 211)), I realized I could do the following: foreach v of newlist x1 x2 x3... { cap gen `v'1972 = (`v'1980-`v'1970)/10*2+`v'1970 cap gen `v'1976 = (`v'1980-`v'1970)/10*6+`v'1970 ... } That's a good work-around for now, but in the future, is there a way to avoid putting "cap" at the start of each command line? Thank you for your help. Gratefully, Daniel * * For searches and help try: * http://www.stata.com/help.cgi?search * http://www.stata.com/support/faqs/resources/statalist-faq/ * http://www.ats.ucla.edu/stat/stata/