Search code examples
spss

How can I access arguments by their index in SPSS macros?


I have defined a macro as:

DEFINE !testMacro (actDS = !TOKENS(1) 
                  /var = !TOKENS(1)
                  /factors = !ENCLOSE('(',')'))

And I call it this way:

!testMacro actDS=testDataSet var=var1 factors=(A B C).

My question is how can I access the factors by index in the macro? For example, I want to split the dataset by the second factor (B).


Solution

  • The usual use of getting a list like factors into the macro is to loop on it and perform the same actions on each (see first example in below syntax).
    If you want to use a single item in the list separately, the easiest way would be to just call it into the macro separately. If you have to call it in the list and still have to use it separately you could play with some of the text functions in the spss macro language (see second example).
    If you have a longer list you can use a loop (like in the third example) to select the specific item you need in the list.

    DEFINE !testMacro (factors = !ENCLOSE('(',')'))
    title 'looping through all factors'.
    !do !i !in(!factors)
    title !quote(!i) .
    !doend
    
    title 'selecting third factor only'.
    !let !fac3=!head(!tail(!tail(!factors)))
    title !quote(!fac3) .
    
    title 'selecting third with a loop'.
    !let !facs=!factors
    !do !i=1 !to 2
    !let !facs=!tail(!facs)
    !doend
    !let !fac3=!head(!facs)
    title !quote(!fac3) .
    !enddefine.
    
    !testMacro  factors=(Aaa Bbb Ccc Ddd Eee Fff).
    
    looping through all factors  
    Aaa  
    Bbb  
    Ccc   
    Ddd  
    selecting third factor only  
    Ccc  
    selecting third with a loop  
    Ccc