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


From   Nick Cox <njcoxstata@gmail.com>
To   statalist@hsphsun2.harvard.edu
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
<boussard@stanford.edu> 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–2014 StataCorp LP   |   Terms of use   |   Privacy   |   Contact us   |   Site index