Announcement

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

  • conditional encode

    It seems that I am blindfolded: Although I tried and looked for about half an hour, I can't see my coding error:

    I want to encode a list of variables *if* the respective variable is of type string, else I simply want to generate a variable with missing values and a label defined with the name of that variable.

    An example of my data:
    Code:
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input str8 rts2270890 byte rts2270892
    "pjduty"   .
    "pjattri1" .
    "pjattri2" .
    "pjattri3" .
    "pjbribes" .
    ""         .
    ""         .
    ""         .
    ""         .
    ""         .
    end
    And here my attempt that fails when encountering variable rts2270892 with the error message "not possible with numeric variable" although I believe that the -if ... else- condition should prevent this:
    Code:
    ocal n = 0
    foreach v of varlist rts* {
       local n = `n'+1
       local ns : di %03.0f `n'
       ds `v', has(type str# strL)
       if "r(varlist)" != "" {
          di "`r(varlist)'"
          encode `v', gen(ba_pt`ns')
       }
       else {
          gen ba_pt`ns' = .
          lab def ba_pt`ns' 1 " "
       }
    }
    Anyone out there who can locate the problem?

  • #2
    Code:
     
     if "r(varlist)" != ""
    If you put r(varlist) between quotes (" ") without evaluating it (` ') , Stata will take "r(varlist)" in the most literal way and compare the string "r(varlist)" to "", which is never true and therefore the if statement with encode will always execute. What you need is:
    Code:
     if "`r(varlist)'" != ""
    An alternative is to use confirm string variable, which is made for these kinds of things.
    Code:
    local n = 0
    foreach v of varlist rts* {
       local n = `n'+1
       local ns : di %03.0f `n'
       capture confirm string variable `v'
       if !_rc {
          di "`r(varlist)'"
          encode `v', gen(ba_pt`ns')
       }
       else {
          gen ba_pt`ns' = .
          lab def ba_pt`ns' 1 " "
       }
    }

    Comment


    • #3
      Thanks a lot Wouter -- solved!

      Comment

      Working...
      X