IBM Support

DO REPEAT and LOOP (when to use what)

Troubleshooting


Problem

I notice that in SPSS there are several command sets which permit repetitive processing. I am referring to LOOP / END LOOP and DO REPEAT / END REPEAT. Can you give me some guidelines on where each of these commands are most useful. Specifically when should I use DO REPEAT, and when should I use LOOP?

Resolving The Problem

The crucial thing to note is that vector requires contiguous variables. That is they must be side by side in the file. DO REPEAT can have non-adjacent variables in its clauses. Loops can be nested to an arbitrary depth. DO REPEAT commands cannot be nested. Much information about these commands can be gleaned from the SPSS reference guide. A salient property of VECTOR with LOOP is that it is able to use indexed sets of variables.

Here are a few examples of each command assuming the active file contains V1 to V4 and W1 TO W4 .

** Programs to construct a SET of difference scores and sum scores .

VECTOR X(4) / Y(4) .
DO REPEAT V= V1 TO V4 / W = W1 TO W4 / X = X1 TO X4 / Y = Y1 TO Y4.
COMPUTE X = V + W.
COMPUTE Y = V - W.
END REPEAT .

VECTOR V = V1 TO V4 / W = W1 TO W4 / X(4) / Y(4) .
LOOP I = 1 to 4 .
COMPUTE X(I) = V(I) + W(I) .
COMPUTE Y(I) = V(I) - W(I) .
END LOOP .

The VECTOR command in the first program will ensure that X1 TO X4 and Y1 TO Y4 will be contiguous in the file .

** Program to construct cross products of two sets of variables.
** The nesting restriction does not allow us to use the DO REPEAT - END REPEAT commands .

VECTOR V = V1 TO V4 / W = W1 TO W4 / VcrW(16).
LOOP I = 1 to 4 .
+ LOOP J = 1 to 4 .
+ Compute Xloc = (I-1)*4 + J .
+ COMPUTE VcrW(XLoc) = V(I) * W(J) .
+ END LOOP
END LOOP .

** DO REPEAT using non-contiguous variables **

DO REPEAT ONE=V1 W1/ TWO=V2 W2 /THREE=V3 W3 /FOUR=V4 W4 /Stuff = Vsum WSum .
COMPUTE Stuff = SUM(ONE,TWO,THREE,FOUR) .
END REPEAT .

But a more streamlined way of doing the above DO REPEAT - COMPUTE - END REPEAT command sequence is listed below:

COMPUTE VSum = SUM(V1 TO V4).
COMPUTE WSum= SUM(W1 TO W4)

[{"Product":{"code":"SSLVMB","label":"IBM SPSS Statistics"},"Business Unit":{"code":"BU059","label":"IBM Software w\/o TPS"},"Component":"Not Applicable","Platform":[{"code":"PF025","label":"Platform Independent"}],"Version":"Not Applicable","Edition":"","Line of Business":{"code":"LOB10","label":"Data and AI"}}]

Historical Number

14456

Document Information

Modified date:
16 April 2020

UID

swg21476044