Announcement

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

  • Restrict on Local in Loop

    I would like to execute a line inside a loop only for one of the categories I loop through. I can easily do it using numeric values in the loop but it doesn't work if I have strings. Using the following code I get the error message hih not found:

    Code:
    foreach sam in hih low {
    
    use data_`sam', clear
    
    if `sam' = hih keep if type_group==1
    
    }

  • #2
    Code:
    if `"`sam'"' = "hih" keep if type_group==1
    When you want to refer to a value of a string, you must enclose it in quotes. That is true as well of `sam', since a macro is a string, and here you want to compare that value, which will be either hih or low, and compare it to the value of the literal string "hih".

    By the way, just as a matter of style, although it is legal to put a conditionally executed command on the same line following -if condition-, and it will produce the intended result for a single command, it's better practice to instead do:
    Code:
    if whatever {
        command_to_be_conditionally_executed
    }
    The reason is that with the single line approach, it is too easy to make the mistake of going back later and adding one or more additional commands to be conditionally executed without enclosing all of them in braces (especially if you also work in languages where indentation alone signifies block nesting), not realizing that only the first would then be subject to the -if- conditioning.

    Comment


    • #3
      Thanks Clyde. I just had to add a second = to make it work.

      Code:
       
       if `"`sam'"' == "hih" keep if type_group==1

      Comment


      • #4
        Oops, yes, sorry about the = instead of ==.

        Comment

        Working...
        X