Search code examples
macrosspss

SPSS - assign a value to a macro argument by manipulating another argument


I am trying to build a macro with 2 arguments: - one of them is being passed when calling the macro, - the 2nd one is a transformation of the first. Basically, I am trying to do a string transformation on the 1st argument, and use the result to run some syntax.

    Define !MyMacro (arg1=!tokens (1), arg2=!DEFAULT(SomeValue) !tokens(1))
    /*what I am trying to achieve is to 
    replace all "-" in arg1 with "_", but the syntax does not work with macro arguments:
    compute !arg2 = replace(!arg1,"-","_").

    /*I need arg 2 to be available further down the syntax, as a variable name:
    fre !arg2.
    !Enddefine.

Any suggestions on to work around this ?


Solution

  • "-" being a special character divides strings into separete tokens in the macro parser. For this reason you can not read a string that contains "-" as a macro argument using !TOKENS(1) (like you did in your example).
    This can cause problems in other cases but here we can turn the bug into a feature: the following macro runs through the separate tokens in !ARG1 and replaces "-" with "_". If there is no "-", there will only be one token in !ARG1 and nothing will change.

    Define !MyMacro (arg1=!cmdend)
    !let !arg2=""
    !do !i !in(!arg1)
    !if (!i="-") !then !let !arg2=!concat(!arg2,"_") !else !let !arg2=!concat(!arg2,!i) !ifend
    !doend.
    title !quote( !arg2).
    freq !arg2 .
    !enddefine.
    
    !MyMacro arg1=turn-into_.
    

    The previous macro will only work with "-" and similar special characters, the following one can be used for any character (though I still set it up for "-"):

    Define !MyMacro (arg1=!cmdend)
    !let !arg2=""
    !do !i = 1 !to !length(!arg1)
    !if (!substr(!arg1,!i,1)="-") !then !let !arg2=!concat(!arg2,"_") !else !let !arg2=!concat(!arg2,!substr(!arg1,!i,1)) !ifend
    !doend.
    title !quote(!arg2).
    freq !arg2 .
    !enddefine.
    
    !MyMacro arg1=turn-into_.