SPSS Macro Arithmetic

SPSS macros are fundamentally a form of string manipulation, and lack any interface for arithmetic. Nonetheless, it is possible to accomplish basic arithmetic through creative use of string functions.

The below macros demonstrate how to operate on externally declared macro values (i.e. define !year() 2021 !enddefine). If passing a parameter into a macro, the !eval() call can be eliminated.


Addition

!a + 1

define !main()
  *Short.
  !let !c = !length(!concat(!blanks(!eval(!a)), !blanks(1)))

  *Readable.
  !let !c = !length(
    !concat(
      !blanks(!eval(!a)),
      !blanks(1)
    )
  )
!enddefine

!a + !b

define !main()
  *Short.
  !let !c = !length(!concat(!blanks(!eval(!a)), !blanks(!b)))

  *Readable.
  !let !c = !length(
    !concat(
      !blanks(!eval(!a)),
      !blanks(!eval(!b))
    )
  )
!enddefine


Subtraction

!a - 1

define !main()
  *Short.
  !let !c = !length(!substr(!blanks(!eval(!a)),2))

  *Readable.
  !let !c = !length(
    !substr(
      !blanks(!eval(!a)),
      2
    )
  )
!enddefine

!a - !b

define !main()
  *Short.
  !let !c = !length(!substr(!blanks(!eval(!a)),!length(!concat(!blanks(!eval(!b)),!blanks(1)))))

  *Readable.
  !let !c = !length(
    !substr(
      !blanks(!eval(!a)),
      !length(
        !concat(
          !blanks(!eval(!b)),
          !blanks(1)
        )
      )
    )
  )
!enddefine


Multiplication

!a * !b

define !main()
  !let !sum = !blanks(0)
  !do !x = 1 !to !eval(!a)
    !let !sum = !concat(!sum, !blanks(!eval(!b)))
  !doend
  !let !c = !length(!sum)
!enddefine


CategoryRicottone