Search code examples
macrosspss

SPSS Macro to create new variable based on 2 existing variables


I am trying to write a macro to perform the following operation:

do if SYSMIS(V2).
compute V3=V1.
ELSE.  
compute V3=V2.
end if.

I tried several approaches, but it always gets stuck on the compute command.


Solution

  • One important thing, you should know about SPSS macros is, that the SPSS macro language is just a "string parser". This means, the text within a DEFINE !ENDDEFINE block is parsed and as an output a syntax code will be created. The variables (beginning with "!") will be substituted by the strings(values) assigned to these variables.

    So the line COMPUTE !var1 = !var2. will produce a compute command, with the variables names assigned to !var1 and !var2.

    On the other hand a command like !IF (SYSMIS(!Var2)) !Var1 = !Var3. makes no sense, because what you actually want is to execute an IF command, while !IF is a conditional macro directive, which 'decides' if some piece of syntax code be generated by the macro (if the condition is met), or not.

    So you solution would look something like this:

    DEFINE !crevar ( !POSITIONAL !TOKENS(1)
                     /!POSITIONAL !TOKENS(1)
                     /!POSITIONAL !TOKENS(1))
       DO IF SYSMIS(!2).
          compute !3=!1.
       ELSE.  
          compute !3=!2.
       END IF.
    !ENDDEFINE.
    
    * Macro call.
    !crevar V1 V2 V3.
    
    EXECUTE.
    

    The macro call above, will be evaluated by the macro parser to the code you have given in your question.