Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • No results shown using foreach

    Hi,

    I am trying to get univariate results for each of a number of variables. Following Nick's example in "How to face lists with fortitude", I tried:

    local intint AgeAtHAART YearsOfVL_FU_afterSuccess400 YearsSpentUndetectable PeakVLBefARVs BaselineCD4 MaxCD4At2y PercentCD4Change AbsIncrease2y RDWatHAART WBCatHAART HgbAtHAART MCVatHAART PLTatHAART SCrAtHAART eGFRHAART SCrAtImmuneFail eGFRImmuneFail AZTd4T_PeriodsDuringObs AZTd4Ttime FolInh_PeriodsDuringObs FolateInhTime ACEI_PeriodsDuringObs ACEItime ARB_PeriodsDuringObs ARBtime RTVperiodsDuringObs RTVtime

    foreach x of var `intint' {
    ranksum `x', by(CD4Above350At2y)
    }

    This yields a varlist required error.

    I also tried:

    foreach var in `intint'{
    ranksum `var', by(CD4Above350At2y)
    }

    This simply yields end of do-file, but no results are shown.

    I searched for foreach here, and didn't find a relevant answer. Elsewhere in the do-file, I have:

    tabstat `intint', by(CD4Above350At2y) columns(statistics) statistics(n p50 p25 p75) longstub varwidth(30)

    , and this behaved exactly as expected, which suggests to me that the local macro intint does contain what it was intended to.

    What am I doing wrong, please?

  • #2
    Welcome to Statalist, Benigno.

    When I copy and paste
    Code:
    sysuse auto, clear
    local intint price mpg rep78
    foreach x of var `intint' {
    ranksum `x', by(foreign)
    }
    into Stata's Do-file Editor window, and then "do" it all at once, I get the results we expect.

    But if I select the first line and run it, then select the second line and run it, then select the three lines of the whole loop, and run them, I get the same error you got.

    The important thing to keep in mind is that local macros vanish when the do-file within which they were created ends. If you look carefully at your results window, you'll see that when you select a few lines to run, those few lines are copied into a temporary do-file and run, so even though all the commands are in the same window in the do-file editor, they are run as separate do-files, and local macros defined in one temporary do-file vanish at the end of that do-file.

    Comment


    • #3
      Thank you very much, William! Indeed, I reproduced your results. Running the entire do-file from beginning to end does yield the expected results. Your explanation was also very helpful, in that it not only gave me a solution, but taught me why it did. Much appreciated.

      Comment

      Working...
      X