Announcement

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

  • if <variable> is in <varlist>...

    Hi,

    I would like to write some code that runs through a list of variables using foreach and, if that variable appears in a previously specified list of variables, for it to do one thing and if not, another.

    Any suggestions?

    Thanks,

    Josh

  • #2
    Here's one way:, illustrated in the auto.dta:

    Code:
    sysuse auto, clear
    
    local previously_specified headroom trunk turn
    
    ds price-length
    local new_list `r(varlist)'
    display `"`new_list'"'
    
    local both: list new_list & previously_specified
    local new_only: list new_list - previously_specified
    
    foreach v of varlist `both' {
        // DO ONE THING
        display "`v'"
    }
    
    foreach v of varlist `new_only' {
        //    DO ANOTHER
        display "`v'"
    }

    Comment


    • #3
      This is great. Thanks Clyde. One modification that I made is that once I'd defined the local `both', I typed:

      capture tab `both'
      if _rc==0 {
      // DO THING
      }
      else {
      // DO OTHER THING
      }

      Comment


      • #4
        Yes, that would be simpler. Not sure why I chose the more complicated approach with `new_only'.

        I'm not sure about that -tab `both'- command. If `both' consists of more than two variables, you'll just get a -capture-d error and no output.

        Comment


        • #5
          Under

          Code:
          help macrolists
          there is documentation of

          {local | global} macname : list macname in macname

          So, here's an example. Here all we do here is display the fact of being in or out, but the same logic applies to different actions.

          Code:
          local wanted a b c
          
          foreach q in a b c d e {
              if `: list q in wanted' di "`q' is on the wanted list"
              else di "`q' is not on the wanted list"
          }
          
          a is on the wanted list
          b is on the wanted list
          c is on the wanted list
          d is not on the wanted list
          e is not on the wanted list

          Comment


          • #6
            Thanks Nick. That is a much more efficient way of doing it.

            Comment

            Working...
            X