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]

From |
Nick Cox <njcoxstata@gmail.com> |

To |
statalist@hsphsun2.harvard.edu |

Subject |
Re: st: Macro parsing question. |

Date |
Thu, 14 Feb 2013 09:54:02 +0000 |

Parsing is not the issue here; it's what happens in a loop. The code can be simplified to loc list2 a b c foreach k of loc list2 { if "a" == "`k'" loc d % else loc d Value } di "`d'" As Amadou says, this is what happens . loc list2 a b c . foreach k of loc list2 { 2. if "a" == "`k'" loc d % 3. else loc d Value 4. } . di "`d'" Value So, what's happening? The loop is cycling over "a" "b" "c" and the code sets -d- to "%" if each of these is equal to "a", otherwise to "Value". We can do this step by step. Is "a" == "a"? Yes. Set -d- to "%" Is "a" == "b"? No. Set -d- to "Value". Is "a" == "c"? No. Set -d- to "Value". Once the loop is done, -d- is still "Value". In fact, the loop can be short-circuited. Only the last element in the list has an effect on -d- that survives beyond the loop, so it boils down to local d = cond("a" == "c", "Value", "%") Nick . loc list2 a b c . foreach k of loc list2 { 2. if "a" == "`k'" loc d % 3. else loc d Value 4. } . di "`d'" Value On Thu, Feb 14, 2013 at 9:24 AM, Amadou DIALLO <stata.diallo@gmail.com> wrote: > I spent the night programming some stuffs but cannot understand why I > don't obtain the expected results. I was expecting "%" but got > "Value". What am I doing wrong? > > noi se tr on > loc list1 a > loc list2 a b c > loc d > foreach j of loc list1 { > foreach k of loc list2 { > if "`j'" == "`k'" loc d % > else loc d Value > } // foreach k > } > di "`d'" * * 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/

**Follow-Ups**:**Re: st: Macro parsing question.***From:*Nick Cox <njcoxstata@gmail.com>

**References**:**st: Macro parsing question.***From:*Amadou DIALLO <stata.diallo@gmail.com>

- Prev by Date:
**Re: st: Macro parsing question.** - Next by Date:
**Re: st: Macro parsing question.** - Previous by thread:
**Re: st: Macro parsing question.** - Next by thread:
**Re: st: Macro parsing question.** - Index(es):