Differences between revisions 5 and 6
Revision 5 as of 2023-01-13 21:06:19
Size: 2531
Comment:
Revision 6 as of 2023-01-13 21:06:30
Size: 2530
Comment:
Deletions are marked like this. Additions are marked like this.
Line 110: Line 110:
Advanced looping can be handled through macro programming. See [[SPSS/Macro/Loopings|here]] for examples. Advanced looping can be handled through macro programming. See [[SPSS/Macro/Looping|here]] for examples.

SPSS Looping

SPSS offers a couple options for looping, but overall is less flexible as compared to other languages.


Do Repeat

The DO REPEAT ... END REPEAT command loops over...

  • arbitrary sequences
  • variable ranges (either existing or new)
  • integer ranges

This command is only valid for data transformation commands (i.e. COMPUTE).

Multiple sequences/ranges can be iterated over in parallel as long as each has the same number of elements.

do repeat X=A B C D E / Y=new1 to new5 / Z=1 to 5.
  if (original=Z) Y=ltrim(rtrim(X)).
end repeat.

To print the evaluated loop syntax, use END REPEAT PRINT.

Because only transformation commands are valid inside DO REPEAT, it isn't possible to do nested looping with it.


Loop

The LOOP ... END LOOP command can arbitrarily loop.

Indefinite Looping

The LOOP command on its own will loop indefinitely (but actually until a maximum depth is reached). A warning will be emitted.

loop.
  compute sentence = replace(sentence,'  ',' ').
end loop.

While Loop

There are two options for a conditional while loop.

First, use the if subcommand on END LOOP. Note that this will still run once, as the condition won't be checked until then.

loop.
  compute sentence = replace(sentence,'  ',' ').
end loop if char.index(sentence,'  ') = 0.

Second, use the if subcommand on LOOP.

loop if char.index(sentence,'  ') > 0.
  compute sentence = replace(sentence,'  ',' ').
end loop.

Integer Range

An explicit number of repetitions can be specified.

loop X=1 to 3.
  compute sentence = replace(sentence,'  ',' ').
end loop.

The variable X is created by the LOOP command and it will persist in the dataset. In the above example it will have a final value of 4. To avoid persistence, consider using a scratch variable (i.e. #i).

The full specification is LOOP <VARIABLE> = <START> TO <END> BY <STEP>.

Variable Range

The integer range method can be combined with vectors to achieve looping over variables.

vector new(4).
loop #i = 1 to 4.
  compute new(#i) = (original=#i).
end loop.


Macros

Advanced looping can be handled through macro programming. See here for examples.


CategoryRicottone

SPSS/Looping (last edited 2023-06-12 15:43:48 by DominicRicottone)