help wfex_loops: Examples of foreach loops

List of examples

1. Adding a counter to a loop.
2. Save information from summarize to a matrix.
3. Save ttest results to a matrix.

1. Add a counter to a loop

local counter = 0
foreach varname in warm yr89 male white age ed prst {
local ++counter
local varlabel : variable label `varname'
display "`counter'. `varname'" _col(12) "`varlabel'"
}

2. Save results from summarize to a matrix

local sdvars "Bsdnei Bsdsoc Bsdchld Bsdfrnd"
local nvars : word count `sdvars'
matrix stats = J(`nvars',2,.)
matrix colnames stats = Pct1s N
matrix rownames stats = `sdvars'
local irow = 0
foreach varname in `sdvars' {
local ++irow
quietly sum `varname'
local samplesize = r(N)
local pct1 = r(mean)*100
matrix stats[`irow',1] = `pct1'
matrix stats[`irow',2] = `samplesize'
}

3. Save ttest results to a matrix

matrix stats = J(5,6,-99)
matrix colnames stats ///
= FemMn FemSD MalMn MalSD t_test t_prob
matrix rownames stats = `varlist'
local irow = 0
foreach var of varlist `tenvars' {
local ++irow
quietly ttest `var', by(female)
matrix stats[`irow',1] = r(mu_2) // female mean
matrix stats[`irow',2] = r(sd_2) // female sd
matrix stats[`irow',3] = r(mu_1) // male mean
matrix stats[`irow',4] = r(sd_1) // female sd
matrix stats[`irow',5] = r(t) // t-value
matrix stats[`irow',6] = r(p) // p-value
}

Also see

Chapter 4 of the Workflow book; foreach; forvalues; Workflow