Differences between revisions 1 and 5 (spanning 4 versions)
Revision 1 as of 2021-09-07 16:26:53
Size: 1692
Comment:
Revision 5 as of 2023-01-13 21:00:49
Size: 1894
Comment:
Deletions are marked like this. Additions are marked like this.
Line 3: Line 3:
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 [[SPSS/MacroStringFunctions|string functions.]] SPSS macros are fundamentally a form of string manipulation, and lack any interface for arithmetic. It is possible to accomplish basic arithmetic through creative use of [[SPSS/Macro/StringFunctions|string functions]].

Note that the below macros demonstrate how to operate on externally declared macros (e.g. `define !year() 2021 !enddefine`). If passing a value into a macro as an argument, the `!eval()` call can be eliminated.

SPSS Macro Arithmetic

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

Note that the below macros demonstrate how to operate on externally declared macros (e.g. define !year() 2021 !enddefine). If passing a value into a macro as an argument, 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

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