foreach stata code example

Example 1: use forvalues stata

> local mcode 0
> local month jan feb mar apr
> foreach m of local month {
    local mcode = `mcode' + 1
    display "`mcode': `m'"
   }
1: jan
2: feb
3: mar
4: apr

Example 2: use forvalues stata

> forvalues i=1/12 {
    generate warm`i'=1 if fmtemp`i' > fmtemp`i'[_n-1]
    replace warm`i'=0 if fmtemp`i' <= fmtemp`i'[_n-1]
    replace warm`i'=99 if year==2013
  }
 
* see the results
> list year fmtemp1-fmtemp3 warm1-warm3, clean 

       year   fmtemp1   fmtemp2   fmtemp3   warm1   warm2   warm3  
  1.   2013      39.2      37.4        41      99      99      99  
  2.   2014      30.2      37.4        41       0       0       0  
  3.   2015      35.6      30.2      44.6       1       0       1

Tags:

Misc Example