Bookmark and Share

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


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

Re: st: Loop with capture


From   Daniel Escher <descher@nd.edu>
To   statalist@hsphsun2.harvard.edu
Subject   Re: st: Loop with capture
Date   Wed, 24 Oct 2012 16:03:17 -0400

Thanks, Nick.


On Wed, Oct 24, 2012 at 3:31 PM, Nick Cox <njcoxstata@gmail.com> wrote:
> If I understand this correctly, it looks, and is, difficult because
> you have separate variables for separate years 1970, 1980, 1990. I
> recommend a -reshape- long and then most things you might want to do
> will be easier, including the interpolation (if that's what is).
>
> reshape long x1 x2 x3, i(whatever) j(year)
>
> Nick
>
> On Wed, Oct 24, 2012 at 7:53 PM, Daniel Escher <descher@nd.edu> wrote:
>
>> 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.
> *
> *   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/
*
*   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/


© Copyright 1996–2014 StataCorp LP   |   Terms of use   |   Privacy   |   Contact us   |   Site index