Announcement

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

  • Using -capture confirm- with wildcard *

    Dear Statalist,

    Unless I'm wrong, capture confirm doesn't seem to work with wildcards (I want to check whether there is at least one variable matching the pattern, say, vargroup_*, and depending on the result, do different actions). Is there a way to work around this limit? I tried using

    Code:
    unab v : vargroup_*
    capture confirm variable `v'
    But in the case where there is no variable matching the pattern, the code won't work. How can I take this into account?

    Thank you very much for the help. I wish you all a happy new year.

  • #2
    What precisely do you think doesn’t work, as if confirm doesn’t work, the point of capture is to eat the error?

    What error code do you get? It should be accessible.

    (I am away from Stata at the moment, and can’t check myself.)

    Comment


    • #3
      Nick : Thank you for your reply. I meant that

      Code:
      unab v : vargroup_*
      won't work if there is no variable matching this pattern (error r(111)), which makes completely sense, but what I want to do is play around the fact that variables matching a pattern don't exist to perform an action.

      In other words, I'd like something like :

      - check if a set of variables following the same pattern exists :
      IF it exists then do regression 1 including this set

      IF it doesn't exist then do regression 2 that do not contain this set
      Last edited by Adam Sadi; 02 Jan 2024, 06:47.

      Comment


      • #4
        if `v' is empty, the resulting command doesn't match the required syntax for the -confirm variable- command, which requires at least one variable name to be specified or else it returns error code 111.You can use an -if- command to test for `v' empty, without any confirm command.
        Last edited by Daniel Feenberg; 02 Jan 2024, 06:54.

        Comment


        • #5
          I came here to second Daniel's post. In effect, -unab- is doing the "validation" of the namespace for you. Here's a sketch of how you might use this.

          Code:
          unab v : myvar_*
          if "`v'"=="" {
            // NO VARIABLE FOUND. DO SOMETHING.
          }
          else {
            // DO SOMETHING ELSE.
          }

          Comment


          • #6
            If the variable specification does not match any variables in the dataset, unab will exit with an error message. Use capture prefix with unab and check for an error code.

            Code:
            capture unab v : myvar_*
            if c(rc) {
                // failed to mach variable specification
            }
            else {
                // `v' contains the matched variables
            }

            Comment

            Working...
            X