Announcement

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

  • Foreach loop not working

    Trying to run a regression on several variables, as below:

    local brain_volumes TIV_SPM BRAIN_SPM Brain_percent_TIV OrbitofrontalLEFTTIV OrbitofrontalRIGHTTIV SupraTempLEFTTIV SupraTempRIGHTTIV MedialParietalLEFTTIV MedialParietalRIGHTTIV LateralParietalLEFTTIV LateralParietalRIGHTTIV SensoryLEFTTIV SensoryRIGHTTIV MedialoccLEFTTIV MedialoccRIGHTTIV

    foreach v of local brain_volumes {
    bootstrap, reps(2000) seed(101): regress `v' c.AAS i.ScannerCategory
    predict `v'_res, resid
    summarize `v'_res
    }

    There is no error but nothing happens and the log just shows the command. I've tested each element outside of the loop, and they each work.

    I've also tried:

    foreach v of brain_volumes TIV_SPM BRAIN_SPM Brain_percent_TIV OrbitofrontalLEFTTIV OrbitofrontalRIGHTTIV SupraTempLEFTTIV SupraTempRIGHTTIV MedialParietalLEFTTIV MedialParietalRIGHTTIV LateralParietalLEFTTIV LateralParietalRIGHTTIV SensoryLEFTTIV SensoryRIGHTTIV MedialoccLEFTTIV MedialoccRIGHTTIV {
    bootstrap, reps(2000) seed(101): regress `v' c.AAS i.ScannerCategory
    predict `v'_res, resid
    summarize `v'_res
    }

    which throws up "invalid syntax r(198);"

    I've checked all the variables and they are correctly named and formatted.

    I've used a very similar loop with a different variable list with no issues.

    Any help troubleshooting would be really appreciated! Thank you!


  • #2
    Welcome to the Stata Forum / Statalist,

    To start, please read the FAQ. There you’ll find how to share data/command/output.

    That said, you may start with - foreach var of varlist-
    Best regards,

    Marcos

    Comment


    • #3
      This can happen when you run the code in chunks, so that the contents of a local macro defined in one place are not visible in another. It's not an error in itself to refer to an empty local macro and the consequence would be as reported, that nothing happens.

      As reported the second block of code is quite wrong. of local is among the legal forms for foreach but of brain_volumes is not.

      A check is to attempt to display the contents of the local macro just before you try to execute the first loop. In any case, try to run all the code at once, say from a do-file editor window.

      Comment

      Working...
      X