Search code examples
macrosspss

Dynamic variable name referencing in SPSS syntax


I want to do certain actions on groups of variables. Each group has a specific index in the name. I don't want to repeat the syntax for each group. Is there a way to dynamically reference the variable names?

Below is the syntax. The 207 is the index that changes for each group of variables.

DO REPEAT aa= M9_207_1 to M9_207_99.
.....
END REPEAT.
EXECUTE.

Solution

  • You can use a macro to do this.

    first define the macro:

    define !MyMacro ()
    !do !ndx=201 !to 207
      DO REPEAT aa= !concat("M9_",!ndx,"_1") to !concat("M9_",!ndx,"_99").
      .....
      END REPEAT.
      EXECUTE.
    !doend
    !enddefine.
    

    then call it:

    !MyMacro.
    

    The macro defined here will run through indexes 201, 202, 203, etc'. If you need a more specific list of indexes, you can define the macro this way:

    define !MyMacro (!pos=!cmdend)
    !do !ndx !in(!1)
      DO REPEAT aa= !concat("M9_",!ndx,"_1") to !concat("M9_",!ndx,"_99").
      .....
      END REPEAT.
      EXECUTE.
    !doend
    !enddefine.
    

    and then call it, giving the indexes (you have go specify each index individually):

    !MyMacro 207 311 501 502 503 504 785.