Search code examples
pythonfunctionspss

SPSS - Python functions in startup script


Following up on this question and it's answer, I am trying to create an SPSS custom function in Python, to use in SPSS syntax.

I have a program that works well in a syntax:

begin program.

import spss,spssaux, sys

def CustomFunction ():
   #function code here   

CustomFunction()

end program.

But I want the CustomFunction()to be available in "normal" SPSS syntax.


Solution

  • Standard syntax does not use Python code nor does it add Python functions to, say, the transformation system. If you have a Python module, its contents can be used directly by just importing that module. And don't worry about importing it multiple times as Python is smart about ignoring redundant imports.

    If you want to use Python code as regular syntax, you need to create an extension command. These have standard-style syntax but are implemented in Python (or R or Java). There are many of these either installed with Statistics or installable from the Utilities menu (or the Extensions menu in V24). Information on how to write these is in the Python help doc and related topics in the Help system.

    As an example, the SPSSINC TRANS extension command makes Python functions available as transformation code. If CustomFunction, say, creates or transforms a variable casewise and is stored in mymodule.py, it might be invoked like this.

    SPSSINC TRANS RESULT=newvar
    /FORMULA "mymodule.CustomFunction(x,y,z)".

    Extension commands are automatically loaded when Statistics starts, so there is no need for a startup script.