Announcement

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

  • How to loop over string content of a variable name?

    Hi statalisters,

    I created a loop to convert all the variables of my dataset containing binary text values such as No/Yes into numeric variables with 0/1 and No/Yes labels. This is an example because I think the content of the variable is not important here.

    I named the numeric counterpart just adding _bis to the original variable name.

    Now, I would like to delete the original variables if their numeric counterpart (variable_bis) exists.

    Here's what I tried:

    Code:
    gen A=""
    gen B=.
    gen C=""
    gen D=""
    gen E=.
    gen F="" ** this one contains text different from No/Yes so not converted in the loop
    gen A_bis=.
    gen C_bis=.
    gen D_bis=.
     
    foreach var of varlist  A-F {
    drop `var' if `var'=="`var'"_bis
    }
    The code returns an "invalid synthax".

    I tried a bunch of things including adding double quotes around the first `var' after if, single quotes around "`var'"_bis or trying to create a local macro with variable names but I was not able to solve the problem.
    I guess this is a matter of properly calling the variable name and not its content but I can't figure out the place of the single or double quotes.

    Can somebody help please?

    Best,
    Maud




  • #2
    -drop if- works on observations not on variables. Use -drop `var'_bis - .Also you don't have B_bis variable, so loop might return error. Use 'capture' before drop:

    Code:
    foreach var of varlist  A-F {
    capture drop `var'_bis
    }
    Roman

    Comment


    • #3
      #2 is closer in syntax to what you want, but if I understand correctly has the variable sets the wrong way round,

      But to expand on Roman Mostazir 's point there is a big difference between the if command and the if qualifier.

      Alternatively, you could turn this around.


      Code:
      foreach v of var *_bis {  
      
           local V = subinstr("`v'",  "_bis", "", .)
           capture drop `V'
      
      }

      Comment


      • #4
        Apologies, I misread. Nick Cox is correct#3. You want to keep the original if "*_bis" exists and Nick has provided the solution for that.
        Roman

        Comment


        • #5
          Great thank you both!

          Comment

          Working...
          X