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: foreach help


From   Nick Cox <[email protected]>
To   [email protected]
Subject   Re: st: foreach help
Date   Tue, 18 Dec 2012 19:11:22 +0000

The problem is not to do with your loop as such. You are using "  " as
needed outside the loop but not inside.

levelsof category, local(levels)

foreach i of local levels {
          sum nonlmct if category == "`i'", meanonly
          di "`i'{col 25}"  r(sum)
}

In the absence of " ", Stata looks for a variable with the name of the
string you specify, and here fails at the first fence.

That said

tabstat nonlmct, by(category) s(sum)

is a simpler solution to your specific problem.

Nick

On Tue, Dec 18, 2012 at 6:37 PM, Tina Hernandez-Boussard
<[email protected]> wrote:

> I was hoping that someone might help me trouble shoot my foreach loop.  Seems very simple, yet I keep getting an error.  My code is:
>
> . levelsof category , local(levels)
> `"allergies"' `"assessment and plan"' `"history of present illness"' `"laboratory results"' `"medications"' `"past medical history
>> "' `"physical exam"' `"plan"' `"social history"'
>
> . foreach 1 of local levels {
>   2. sum(nonlmct ) if category ==`1'
>   3. di r(sum)
>   4. }
> allergies not found
> r(111);
>
>
> Yet if I run this code outside of the loop I get an the below:
>
> . sum(nonlmct ) if category =="allergies"
>
>     Variable |       Obs        Mean    Std. Dev.       Min        Max
> -------------+--------------------------------------------------------
>      nonlmct |        72         4.5    2.897303          2         12
>
> . di r(sum)
*
*   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–2018 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   Site index