SPSS Looping
SPSS offers a couple options for looping, but overall is less flexible as compared to other languages.
Contents
Arbitrary Lists
The DO REPEAT command can loop over arbitrary, fixed-length lists.
do repeat X='A' 'B' 'C' 'D' 'E'. if ltrim(rtrim(foo))=X bar=1. end repeat.
Integer Ranges
The DO REPEAT command can loop over an integer range.
do repeat Y=1 to 5. if foo=X bar=1. end repeat.
The LOOP command can be used similarly.
loop #y=1 to 5 by 1. if foo=#y bar=1. end loop.
Variable Lists
The DO REPEAT command can loop over variables. If the variables are not pre-existing, a range is extrapolated from the variable names.
do repeat Z=new1 to new5. compute Z=foo. end repeat.
A similar effect can be acheived by using the LOOP command with a vector.
vector new(4). loop #z = 1 to 4. compute new(#z) = (foo=#z). end loop.
Conditional Looping
The LOOP command can loop a variable number of times, based on either a 'while' or a 'break' condition. Specify the IF option on the LOOP command for the former behaviuor, or on the END LOOP command for the latter.
loop. compute foo = replace(foo,' ',' '). end loop if char.index(foo,' ') = 0. loop if char.index(foo,' ') > 0. compute foo = replace(foo,' ',' '). end loop.
Indefinite Looping
The LOOP command can also be made loop indefinitely, if no IF option is specified.
loop. compute foo = replace(foo,' ',' '). end loop.
Macros
Advanced looping can be handled through macro programming. See here for examples.