Announcement

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

  • Using the foreach command

    Hello,

    I am using STATA 15 and wide-format dataset.

    My aim is to create a new variable (my data is confidential but as an example I will call it "newv") which I want to have a value of 1 or 0.

    The value should be 1 if any of the values in a long list of other alphanumeric variables in the dataset contain a certain alphanumeric code.

    As an example of the list of variables I will use "toronto" "paris" "rome" "madrid" here.

    varname: toronto paris rome madrid
    value: A1 b2 C3 D4


    The list of variables in reality is very long and involves a lot of lines of code, so I am trying to use the foreach command.

    The code I am using is :

    gen newv=0
    for each v of varlist toronto paris rome madrid {
    replace newv=1 if strpos (v,"A1")>0
    }

    However, when I do this STATA says "{ required"

    I thought I had put the braces in the correct place so I'm not sure where I am going wrong?

    Any advice would be much appreciated,
    Karyn

  • #2
    this MAY be an issue of not the best error message; I see two other errors: (1) "foreach" should be one word; (2) in your replace line, the "v" needs to be surrounded by "`" on the left and "'" on the right; see
    Code:
    help foreach
    also, your code would be easier to read if you used CODE blocks - see the FAQ

    Comment


    • #3
      Yes, what Rich says. Also, no space between strpos and opening bracket.
      In future posts, please use dataex to post and example, and please copy exact code.
      See the FAQ on dataex: https://www.statalist.org/forums/help#stata
      Although the code you posted had issues, it does not produce the error you mentioned.
      Without knowing your exact code, it is not possible to troubleshoot correctly.

      Code:
      * Example generated by -dataex-. To install: ssc install dataex
      clear
      input str2(toronto paris rome madrid)
      "A1" "b2" "C3" "D4"
      end
      
      gen newv=0
      foreach v of varlist toronto paris rome madrid {
      replace newv=1 if strpos(`v',"A1")>0
      }

      Comment

      Working...
      X