Differences between revisions 2 and 8 (spanning 6 versions)
Revision 2 as of 2021-09-07 16:28:53
Size: 1891
Comment:
Revision 8 as of 2023-06-14 15:47:50
Size: 1852
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 do not offer any numeric functions or operators directly, but certain forms of arithmetic can be hacked with [[SPSS/Macro/StringFunctions|string functions]].
Line 5: Line 5:
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. Note that these examples demonstrate operations on externally-declared macros (e.g. `define !year() 2021 !enddefine`). If values are instead passed as [[SPSS/Macro/Arguments|arguments]], the `!EVAL` can be eliminated.

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)