Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 39 ยท Syntax and Automation

SPSS Macros, DO REPEAT Loops and Python Automation

Automate repetitive SPSS work with DO REPEAT, VECTOR and LOOP, DEFINE macros, INSERT files and BEGIN PROGRAM PYTHON3 scripts that submit commands.

When the same operation repeats over 20 questionnaire items or 12 monthly variables, copy-pasting commands is slow and error-prone. SPSS offers several automation tools, from simple to powerful. Use the simplest one that solves the problem.

DO REPEAT: one command for many variables

DO REPEAT applies the same transformation to a list of variables.

Text
DO REPEAT old = q1 q2 q3 q4 q5
        / new = q1_r q2_r q3_r q4_r q5_r.
  COMPUTE new = 6 - old.
END REPEAT.
EXECUTE.

Rules: you declare one or more stand-in names (old, new) with equal-length lists, and use them inside the block as if they were variables. Only transformation commands (COMPUTE, IF, RECODE, COUNT, DO IF) are allowed inside; it is not a general loop.

VECTOR and LOOP

A vector gives array-style access to a set of variables, and LOOP repeats commands.

Text
VECTOR item = q1 TO q10.
VECTOR rev(10, F2).
LOOP #i = 1 TO 10.
  COMPUTE rev(#i) = 6 - item(#i).
END LOOP.
EXECUTE.

Variables that start with # are scratch variables: they exist only during the transformation pass and are not saved. LOOP also works with IF conditions and BREAK. A LOOP runs once per case, so LOOP #i = 1 TO 10 loops over items within each case, not over cases.

INSERT: build a pipeline

INSERT runs another syntax file inside this one, so you can split a project into parts:

Text
INSERT FILE='C:\Projects\survey\01_import.sps' ERROR=STOP.
INSERT FILE='C:\Projects\survey\02_clean.sps' ERROR=STOP.
INSERT FILE='C:\Projects\survey\03_analysis.sps' ERROR=STOP.

ERROR=STOP halts when a command in the inserted file fails. A master script made of INSERT lines is the SPSS version of a build script.

DEFINE: macros

A macro is a named piece of text that SPSS expands before running. Use it to reuse a block with different arguments.

Text
DEFINE !describe (var = !TOKENS(1)).
FREQUENCIES VARIABLES=!var
  /STATISTICS=MEAN MEDIAN STDDEV.
!ENDDEFINE.

!describe var=age.
!describe var=income.

Macros can take several arguments, include loops (!DO !i !IN (...) ... !DOEND), and conditionals (!IF ... !THEN ... !IFEND). Macro names start with !, and arguments are replaced as text, which makes errors harder to read; use them for bigger repeated blocks and use DO REPEAT for transformations.

Python Stand-in: macro-style expansion in Python

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python programmability

SPSS ships with a Python integration (the Essentials for Python). Python code lives in a program block and talks to SPSS through the spss module:

Text
BEGIN PROGRAM PYTHON3.
import spss
for v in ["age", "income"]:
    spss.Submit(f"DESCRIPTIVES VARIABLES={v}.")
END PROGRAM.
  • spss.Submit() sends one or more syntax commands.
  • spss.Cursor reads and writes data values; spss.Dataset is a higher-level interface.
  • spss.GetVariableCount() and spss.GetVariableName(i) read the dictionary.
  • Python can loop over files, build commands from lists, parse output (with the spssaux helper modules) and call outside libraries (pandas, numpy) if installed.

The code between BEGIN PROGRAM and END PROGRAM is real Python, not SPSS syntax: indentation matters and the commands you send are strings. This repository's lessons cannot run SPSS, so the stand-in below builds the same command strings.

Python Stand-in: building a batch of commands like spss.Submit would

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

R integration works similarly (BEGIN PROGRAM R.) if R and the integration plug-in are installed.

Production jobs and scheduling

SPSS can run a syntax file without the interface, useful for nightly reports:

  • Production Facility (Utilities menu in older versions) builds a job that runs syntax and exports output.
  • stats.exe -f myjob.sps style batch calls and the spssb batch executable run a .sps unattended on a server, with the data paths in the script.
  • Combine with OMS or OUTPUT EXPORT so the job writes a Word, PDF or Excel report each time.

Exact executable names depend on your version and installation, so check your IBM documentation.

Choosing the right tool

Task Use
Same transformation on many variables DO REPEAT
Array indexing over item sets VECTOR + LOOP
Reuse a command block with arguments DEFINE macro
Run several scripts in order INSERT
Logic, file handling, loops over files Python program block

Common mistakes

  • Using DO REPEAT for non-transformation commands (it only supports transformations).
  • Forgetting !ENDDEFINE. or the periods inside a macro.
  • Wrong indentation in a Python block.
  • Hard-coding the same file path in ten scripts.
  • Starting with a macro when a short DO REPEAT would do.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which command applies the same COMPUTE to a list of variables?

    DO REPEAT replaces stand-in names with each variable in your lists.
  2. 2. What is a scratch variable such as #i?

    Variables starting with # are not saved in the dataset.
  3. 3. How does Python send an SPSS command from a program block?

    spss.Submit runs syntax strings through SPSS.
  4. 4. Which is best to run three syntax files in a fixed order?

    INSERT chains scripts; ERROR=STOP halts the chain on failure.

Summary

  • DO REPEAT and VECTOR/LOOP repeat transformations over variables.
  • INSERT chains syntax files; DEFINE macros reuse command blocks with arguments.
  • BEGIN PROGRAM PYTHON3 gives full Python control through the spss module.
  • Production jobs and batch calls allow unattended runs; pick the simplest tool for each task.

Next: Project: Analysing a Customer Survey