SPSS Macro Arithmetic

SPSS macros do not offer any numeric functions or operators directly, but certain forms of arithmetic can be hacked with string functions.

Note that these examples demonstrate operations on externally-declared macros (e.g. define !year() 2021 !enddefine). If values are instead passed as arguments, the !EVAL 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

SPSS/Macro/Arithmetic (last edited 2023-06-14 15:47:50 by DominicRicottone)