Announcement

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

  • How to check that a variable exists

    Hi,

    I would like to know whether a variable exists or not. I am currently using the following code:

    Code:
    foreach var of varlist q1 q2 q3 {
        capture confirm variable `var'_e
        if !_rc {
            display "`var'_e exists"
        }
        else {
            display "`var'_e does not exist
        }
    }
    However, with the code above, even if q1_e does not exist but q1_e_other does, it will display "q1_e exists" while I should be getting "q1_e does not exist". How can I change my code to display the correct message?

    Thank you

  • #2
    Hi there,

    You'll just need to add the 'exact' option to the confirm command:

    Code:
    foreach var of varlist q1 q2 q3 {
        capture confirm variable `var'_e, exact
        if !_rc {
            display "`var'_e exists"
       }
       else {
          display "`var'_e does not exist
       }
    }
    Alternatively, you could 'set varabbrev off' entirely if you wish. 'novarabbrev' can also be handy to know of in some other situations.

    Comment

    Working...
    X