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: Overlapping Loops


From   Nick Cox <[email protected]>
To   [email protected]
Subject   Re: st: RE: Overlapping Loops
Date   Wed, 18 Jan 2012 21:16:00 +0000

Working backwards, and using Scott's examples as well, you should learn that

1. -forvalues- needs to see a number in that position.

2. If you have the constants you need in variables, it is better
practice to put them in local macros.

3. If you have something like

local J = 10
forval j = 1/`J' {

that's OK because Stata evaluates the local macro before -forvalues-
gets to work and so -forvalues- sees

forval j = 1/10 {

and the rules about seeing numbers are satisfied.

Nick

On Wed, Jan 18, 2012 at 7:58 PM, Bader Alhashel <[email protected]> wrote:
> Thanks for getting back to me Nick. Please bare with me as I am not
> quite affluent in Stata's programming.
>
> numberofpeople1 up to numberofpeople17 are numeric variables. Do you I
> need to define it?
>
> On Wed, Jan 18, 2012 at 2:45 PM, Nick Cox <[email protected]> wrote:
>> That's not a problem so far as I can see. Consider first time round the outer loop, so `i' = 1.
>>
>> The inner statements become
>>
>> gen ceo_photo1 = 0 if photo1==1
>>
>> forvalues j=1/numberofpeople1 {
>>        replace ceo_photo1=1 if ceo == name`j'_photo1 & ceo_photo1==0
>> }
>>
>> The thing that looks odd now is -numberofpeople1-. Tell us where you define it and what it is.
>>
>> Similarly, what are -numberofpeople2- ... -numberofpeople17-?
>>
>> Basically, it doesn't matter what they are, variables or scalars, as -forval- expects to see an actual number at that place. You could evaluate something on the fly, but that's a different technique.
>>
>> Nick
>> [email protected]
>>
>>
>> -----Original Message-----
>> From: [email protected] [mailto:[email protected]] On Behalf Of Bader Alhashel
>> Sent: 18 January 2012 19:27
>> To: statalist
>> Subject: st: Overlapping Loops
>>
>> I am trying to write two over lapping "foreach" loops however I keep
>> getting an invalid syntax error. I don't know why but I am guessing it
>> is because of the local macro in the first loop is not recognized in
>> the second loop. This is the code I am trying to run.
>>
>> forvalues i = 1/17 {
>> gen ceo_photo`i'=0 if photo`i'==1
>> forvalues j=1/numberofpeople`i' {
>> replace ceo_photo`i'=1 if ceo == name`j'_photo`i' & ceo_photo`i'==0
>> }
>> }
>>

*
*   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