Announcement

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

  • Do not Execute Part of Code if Condition is Met

    I would like to skip and not execute part of a code if a certain condition is met. In the following example I would like not summarize if var==price or var==rep78 and mpg==12 or mpg==14. I think I could do it with if else, but it would be very tedious to code it. Any other suggestion would be greatly appreciated.

    Code:
    sysuse auto.dta
    
    levelsof mpg, local(mpg)
    
    foreach i in `mpg' {
        
        foreach var in price rep78 headroom trunk weight length turn displacement gear_ratio foreign {
            
            sum `var' if mpg==`i'    
            
        }
        
    }

  • #2
    Yes, it can be done with the -if- command, and there is nothing tedious about it:
    Code:
    sysuse auto.dta
    
    levelsof mpg, local(mpg)
    
    foreach i in `mpg' {
        if !inlist(`mpg', 12, 14) {
            foreach var in price rep78 headroom trunk weight length turn displacement gear_ratio foreign {
                if !inlist("`var'", "price", "rep78") {
                    sum `var' if mpg==`i'    
                }
            }
        }
    }
    But there are better ways to do this. To exclude price and rep78 from the loop over variables, you could just omit them from the varlist in the first place. Similarly, you can exclude 12 and 14 from local macro mpg. So putting these together:

    Code:
    sysuse auto.dta, clear
    
    levelsof mpg if !inlist(mpg, 12, 14), local(mpg)
    local mpg: list mpg - exclude
    
    foreach i in `mpg' {
            foreach var in headroom trunk weight length turn displacement gear_ratio foreign {
                    sum `var' if mpg==`i'    
            }
    }

    Comment

    Working...
    X