Announcement

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

  • capture command for the non existence of a variable

    Hello!
    How can I use the capture command confirm variable to do sth if a variable exists and other think is the variable doesn't exist? Is it possible to associate the capture command to a non existence of a variable?

    Ex:
    capture confirm variable teste if c(rc) == { display "variable teste exists" } how can I display, por ex, "variable teste does not exist" if it is the case?

  • #2
    Are you looking for something like this?

    .ÿsysuseÿauto
    (1978ÿAutomobileÿData)

    .ÿforeachÿvarÿinÿmakeÿnowayÿ{
    ÿÿ2.ÿcaptureÿconfirmÿvariableÿ`var'
    ÿÿ3.ÿifÿ_rcÿ{
    ÿÿ4.ÿdisplayÿinÿsmclÿasÿerrorÿ"Variableÿ"ÿasÿinputÿ"`var'ÿ"ÿasÿerrorÿ"doesn'tÿexist!"
    ÿÿ5.ÿ}
    ÿÿ6.ÿ}
    Variableÿnowayÿdoesn'tÿexist!


    Comment


    • #3
      Originally posted by Paula de Souza Leao Spinola View Post
      . . . to do sth if a variable exists and other think is the variable doesn't . . .
      I neglected to illustrate it, but just add an else condition after the if clause to do something if the variable exists in the dataset. The sense is reversed in the illustration below, but you can see the basic set-up (i.e., do something when a variable exists and do something else when it doesn't).
      Code:
      foreach var in <list of candidate variables> {
          capture confirm variable `var'
          if !_rc {
              <actions when the variable does exist>
          }
          else {
              <optional error message of your choice>
              <optional actions when the variable does not exist>
          }
      }
      I believe that it's considered good programming form to put the expected outcome first in an if-else section of code. For example, here, if you expect that most of the time the variables will exist, then put the error-free condition if !_rc { first (as illustrated). If, on the other hand, you expect that most of the candidate variables won't exist in the dataset, then make the evaluation if _rc { and put the does-not-exist actions first.

      Comment


      • #4
        Thank you! I wrote a new post where I wrote exactely what I need to do with the capture command. Maybe you can help me! The link is below:

        http://www.statalist.org/forums/foru...be-in-the-list

        Comment

        Working...
        X