2
votes

I've had a tough time getting a simple loop to work in SPSS that isn't based on variables.

In a nutshell, I want to write

!sequentialVars varStr=/Var/ i=/20/.

or similar and get: Var1 Var2 Var3 Var4 Var5 ... Var19 Var20 to put into a cTable or anywhere else that takes a string of variable names.

In pseudo VB it would be:

varString = "AnyVarName"
for i=1 to 20
  newVarList = concatenate(newVarList," ",varString, i)
next i

I can't even echo back the i in an SPSS loop, let alone concatenate it.

Thank you!

1
This document has a functionally equivalent example on page 130 of the PDF, Creating concatenated stub and banner tables.Andy W
That will help with the concatenation, but unless I'm completely missing it, I can't seem to find how to generate sequential variables in the first place. It's not the " + " part, but the numbers of V1 V2 V3. Then it's also the letters of Va Vb Vc. Does that make sense?ARobertson
Ok that makes sense, if the postfix is a number that wouldn't be too hard (letters I am not so sure). I will see if I can whip up an example quick. Most items that don't need the + in between it is not needed, as one can frequently use VAR1 to VAR50 etc.Andy W

1 Answers

1
votes

The example below demonstrates making a list of variables within a macro. What it does is loop through 1 to n, and concatenates the number on the end of the current variable (base_i). Then the X1 + X2 .... is made by just adding on for every variable through the loop. The macro takes the arguments base variable and the number of items.

*making filler data frame.
data list free / V1 (F1.0).
begin data
1
3
5
end data.
dataset name input.

*making a vector list.
vector X(5,F1.0).
do repeat X = X1 to X5.
compute X = RV.BERNOULLI(0.5).
end repeat.

*what I want to do essentially.
ctables
/table X1 + X2.

*now to demonstrate looping through list.
DEFINE !loop_ctable (base = !TOKENS(1)
                     /n = !TOKENS(1))

!DO !I = 1 !TO !n
    !IF (!I = 1) !then
        !LET !base_stub = !concat(!base,"1")
    !ELSE
        !LET !base_i = !CONCAT(!base,!I)
        !LET !base_stub = !concat(!base_stub," + ",!base_i)
    !IFEND
!DOEND

ctables
/table !base_stub.

!ENDDEFINE.

set mprint on.

!loop_ctable base = X n = 5.

I can think of a way to loop through letters (at least through the initial letters of the alphabet), although hopefully this suffices.