* say that you want to look across variables to see * if any of the variables is zero (iszero) * when the variable was FIRST zero (whenzer) * and the number of non missing variables (nonmiss)* you can do this by loopoing across observations * and then looping across variables
* 1. lets make the variables "iszero" "whenzer" and "nonmiss" capture drop iszero whenzer nonmiss gen iszero = . gen whenzer = . gen nonmiss = .
* 2. here is the list of variable we want to work across local array "var1 var2 var3" local numvars : word count `array’
* 3. set up the loop for looping across observations local obsno = 1 while `obsno’ <= _N { * initialize variables local iszero = 0 local whenzer = 0 local nonmiss = 0
* variable number local varno = 1
* 4. loop across variables while `varno’ <= `numvars’ { local varname : word `varno’ of `array’ if (`varname'[`obsno’] != .) { local nonmiss = `nonmiss’ + 1 } if (`varname'[`obsno’] == 0) { if (`iszero’ == 0) { local whenzer = `varno’ } local iszero = 1 }
local varno = `varno’ + 1 }
* 5. make replacements based on looping across observations replace iszero = `iszero’ in `obsno’ replace whenzer = `whenzer’ in `obsno’ replace nonmiss = `nonmiss’ in `obsno’ local obsno = `obsno’ + 1 }