Announcement

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

  • Assign variable names to variable value if the condition is met

    Dear Experts,

    "Wallau" "Bakel" "Weert" "Kempten" "EPLC" are variables.

    I have a following code, where i would like to substitute variable CoC with the variable names that are in the loop, if their values contain "X"

    HTML Code:
    gen CoC = ""
    
    foreach i in "Wallau" "Bakel" "Weert" "Kempten" "EPLC" {
        
        local x "`i'"
        
        replace CoC = `x' if strpos(`i', "X") > 0
    }
    Therefore, if variable Bakel has a value "100X" in, lets say row 1, the output of CoC in row 1 should be Bakel.


    However in return i get the actual variable values instead of variable names.

    Any idea what i did wrong?

    Sincerly,

    Pavlo

  • #2
    Code:
    gen CoC = ""
    
    foreach i in "Wallau" "Bakel" "Weert" "Kempten" "EPLC" {
        replace CoC = "`i'" if strpos(`i', "X") > 0
    }
    Your attempt to make local macro x contain "`i'" does not succeed because Stata strips initial and final quotes from local macro definitions. You could have done it with -local macro x `""`i'""'-. But there is really no reason to create another macro to contain what is already in `i'. You just need to wrap `i' in quotes in the appropriate place.

    Comment


    • #3
      Clyde Schechter Thanks Clyde, exactly what was needed.

      Comment


      • #4
        As the loop is over variable names, can't it be just

        Code:
         foreach i in Wallau Bakel Weert Kempten EPLC {
        That doesn't inhibit treating the loop argument variously as a variable name and as a literal string inside the loop.

        Comment

        Working...
        X