Announcement

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

  • Help with foreach loop in Stata 17

    Please help to write foreach loop correctly. The following produces an error 'variable var not found'

    Code:
    foreach var of varlist V9 V12 V17 {
    replace var = var[.] if var == 9 | var == 8
    }
    while code like this works

    Code:
    replace V9 = V9[.] if V9 == 9 | V9 == 8
    replace V12 = V12[.] if V12 == 9 | V12 == 8
    replace V17 = V17[.] if V17 == 9 | V17 == 8

  • #2
    foreach creates local macro var which needs to be expanded. Also it is unclear what you expect from V9[.], but what you get is a missing value, so better to be explicit. Here is how your loop should be coded
    Code:
    foreach var of varlist V9 V12 V17 {
            replace `var' = . if `var' == 9 | `var' == 8
    }

    Comment


    • #3
      V9[.] works fortuitously in that reference to a value with a missing subscript is treated as a reference to a missing value.

      The error in your loop is different.

      Code:
      foreach var of varlist V9 V12 V17 {
          replace `var' = . if `var' == 9 | `var' == 8
      }
      No loop is needed, as you could use mvdecode instead.
      Last edited by Nick Cox; 08 Dec 2022, 09:04.

      Comment


      • #4
        Originally posted by Jeff Pitblado (StataCorp) View Post
        foreach creates local macro var which needs to be expanded. Also it is unclear what you expect from V9[.], but what you get is a missing value, so better to be explicit. Here is how your loop should be coded
        Code:
        foreach var of varlist V9 V12 V17 {
        replace `var' = . if `var' == 9 | `var' == 8
        }
        Thank you so much! [.] was for changing 8 and 9 variable values to missing

        Comment

        Working...
        X