Search code examples
loopsindexingspssquotation-marks

SPSS: Use index variable inside quotation marks


I have several datasets over which i want to run identical commands. My basic idea is to create a vector with the names of the datasets and loop over it, using the specified name in my GET command:

VECTOR=(9) D = Name1 to Name9.
LOOP #i = 1 to 9.
     GET 
     FILE = Directory\D(#i).sav
     VALUE LABELS V1 to V8 'some text D(#i)'
LOOP END. 

Now SPSS doesn't recognize that i want it to use the specific value of the vector D. In Stata i'd use

local D(V1 to V8)
foreach D{
    ....`D' .....
}

Solution

  • You can't use VECTOR in this way i.e. using GET command within a VECTOR/LOOP loop.

    However you can use DEFINE/!ENDDEFINE. This is SPSS's native macro facility language, if you are not aware of this, you'll most likely need to do a lot of reading on it and understand it's syntax usage.

    Here's an example:

    DEFINE !RunJob ()
    
    !DO !i !IN 1 !TO 9
      GET FILE = !CONCAT("Directory\D(",#i,").sav").
      VALUE LABELS V1 to V8 !QUOTE(!ONCAT("some text D(",#i,")",
    !DOEND
    !ENDDEFINE.
    
    SET MPRINT ON.
    !RunJob.
    SET MPRINT OFF.
    

    All the code between DEFINE and !ENDDEFINE is the body of the macro and the syntax near to the end !RunJob. then runs and executes those procedures defined in the macro.

    This a very simply use of a macro with no parameters/arguments assigned but there is scope for much more complexity.

    If you are new to DEFINE/!ENDEFINE I would actually suggest you NOT invest time in learning this but instead learn Python Program ability which can be used to achieve the same (and much more) with relative ease compared to DEFINE/!ENDDEFINE.

    A python solution to your example would look like this (you will need Python Programmability integration with your SPSS):

    BEGIN PROGRAM.
    for i in xrange(1,9+1):
        spss.Submit("""
        GET FILE = Directory\D(%(i)s).sav
        VALUE LABELS V1 to V8 'some text D(%(i)s)'.""" % locals())
    END PROGRAM.
    

    As you will notice there is much more simplicity to the python solution.