Announcement

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

  • Problem with locals

    Minor but annoying problem with locals. I have a long variable list that I would like to add to a file with the following code. I keep on getting errors for invalid syntax and too few variables specified. I have not been able to find a fix to the code. Any suggestions

    local vars "site_visits_with_case_worker Indoor_Bathroom Porta_Potty washing_Station ADA_Compliant_Shower"

    local num: word count `vars'

    foreach i in 1/`num' {
    local temp `: word `i' of `vars''
    di `temp'
    gen `temp' = .
    }

  • #2
    The first bug I can see in this code is that while

    Code:
    foreach i in 1/`num' {
    is legal, it is not at all what you want. because

    Code:
    1/`num'
    is taken as a single item and when substituted as

    Code:
    local temp `: word 1/`num'  of `vars''
    it is then illegal.

    You probably meant something more like

    Code:
    foreach i of numlist 1/`num'
    which in turn would be better as
    Code:
    forval i = 1/`num'
    but looping over numbers is needless here as the real problem is looping over some names, which you can do directly.

    I would try


    Code:
     
    local vars "site_visits_with_case_worker Indoor_Bathroom Porta_Potty washing_Station ADA_Compliant_Shower"
    
    foreach v in `vars' { 
        di "`v'" 
        gen `v' = . 
    }

    Comment


    • #3
      Thank you! What would you suggest as a good source to teach myself more about these subleties?

      Comment


      • #4
        The University of Wisconsin-Madison has some nice resources you might find helpful. Expand the Data Wrangling section on this page, and take a look at the pages for Stata Programming Essentials and Stata Programming Tools. HTH.
        --
        Bruce Weaver
        Email: [email protected]
        Version: Stata/MP 18.5 (Windows)

        Comment


        • #5
          #3 Modesty aside, https://journals.sagepub.com/doi/pdf...36867X20976340 was a 2020 rewrite of a 2002 tutorial introduction to loops.

          As for whether it is best for you, I can't possibly comment!

          Comment

          Working...
          X