Differences between revisions 4 and 6 (spanning 2 versions)
Revision 4 as of 2023-01-13 20:58:54
Size: 1954
Comment:
Revision 6 as of 2023-06-14 15:46:42
Size: 1845
Comment:
Deletions are marked like this. Additions are marked like this.
Line 1: Line 1:
## page was renamed from SPSS/MacroArithmetic
Line 4: Line 3:
[[SPSS/Macros|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 6: 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 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 do not offer any numeric functions or operators directly, but certain forms of arithmetic can be hacked with 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)