Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 39 ยท Data Preparation

SPSS Compute Variable: Expressions, Functions, IF and COUNT

Create new variables in SPSS with Transform > Compute Variable: arithmetic, SUM and MEAN functions, conditional IF, COUNT, string and date functions, and how missing values propagate.

Compute Variable is the calculator of SPSS. It creates a new variable from an expression made of existing variables, numbers, operators and functions: a body mass index, a total score, a log transformation, a flag for "high spender". You will use it in nearly every project. Its one big trap is missing values, so this lesson spends time on that.

The dialog

Transform > Compute Variable... opens a window with these parts:

  • Target Variable: the name of the variable to create. If the name exists, it is overwritten.
  • Type & Label...: numeric or string, and a label.
  • Numeric Expression: the formula. Build it by typing, or double-click variables, functions and the on-screen calculator keys.
  • Function group and Functions and Special Variables: a browsable list, with a help line for each function.
  • If... (optional): compute only for cases that satisfy a condition.

The equivalent syntax uses COMPUTE, and EXECUTE. or any procedure runs it:

TEXT
COMPUTE bmi = weight / ((height / 100) ** 2).
VARIABLE LABELS bmi 'Body mass index (kg/m2)'.
COMPUTE income_log = LN(income).
EXECUTE.

SPSS does not run transformations the moment you write them. They become pending and run when the next command that reads data (any analysis) or an EXECUTE. arrives. If you add one without a following command, the status bar says "Transformations pending". Add EXECUTE. in syntax files after a block of COMPUTEs.

Operators

Kind Operators
Arithmetic + - * / ** (power), parentheses
Comparison = <> < > <= >= (also EQ NE LT GT LE GE)
Logical AND OR NOT (also `&

** is exponentiation, and ^ is not used. Comparisons return 1 (true), 0 (false) or system-missing. That lets you compute dummy variables in one line:

TEXT
COMPUTE senior = (age >= 65).
COMPUTE heavy_user = (visits > 10 AND rating >= 4).

Common functions

Group Functions
Arithmetic ABS, SQRT, EXP, LN, LG10, RND, TRUNC, MOD, MIN, MAX
Statistical SUM, MEAN, SD, VARIANCE, MEDIAN, NVALID, CFVAR
Missing values MISSING, SYSMIS, VALUE, NMISS
String CONCAT, SUBSTR, UPCASE, LOWER, LTRIM, RTRIM, CHAR.LENGTH, CHAR.INDEX, REPLACE, STRING, NUMBER
Date DATE.DMY, XDATE.YEAR, XDATE.MONTH, DATEDIFF, DATESUM, CTIME.DAYS
Logical ANY(x, a, b, c), RANGE(x, low, high)
Random RV.NORMAL(mean, sd), RV.UNIFORM(low, high), with SET SEED

ANY and RANGE return 1 or 0 and replace long chains of OR:

TEXT
COMPUTE weekend = ANY(weekday, 6, 7).
COMPUTE teen = RANGE(age, 13, 19).

Missing values: the rule you must know

Arithmetic and most functions return system-missing if any input is missing. a + b + c is missing for a case when any of the three is missing. The statistical functions are different: SUM(a, b, c) and MEAN(a, b, c) ignore missing arguments and use the rest.

That is convenient and dangerous. If a respondent answered only one of five items, MEAN(q1 TO q5) returns that single answer as if it were a full scale score. To demand a minimum, put the count after a dot:

TEXT
COMPUTE scale_score = MEAN.4(q1, q2, q3, q4, q5).
COMPUTE total = SUM.4(q1 TO q5).

MEAN.4 returns the mean only when at least four arguments are valid, otherwise system-missing. A common rule is at least 80% of the items.

Python Stand-in: + vs SUM vs MEAN.n with missing values

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.

The third respondent answered a single item. MEAN would still produce 5.00, which is why MEAN.4 is safer. Declared user-missing values behave like system-missing in these functions.

Conditional computing

There are two ways to compute only for some cases.

IF statement (or the If... button in the dialog):

TEXT
IF (age < 30) group = 1.
IF (age >= 30 AND age < 50) group = 2.
IF (age >= 50) group = 3.

Cases that match no IF get system-missing in the new variable.

DO IF / ELSE IF / ELSE / END IF groups several assignments and guarantees only one branch runs:

TEXT
DO IF (MISSING(age)).
  COMPUTE group = $SYSMIS.
ELSE IF (age < 30).
  COMPUTE group = 1.
ELSE IF (age < 50).
  COMPUTE group = 2.
ELSE.
  COMPUTE group = 3.
END IF.
EXECUTE.

Put the missing-value branch first. A missing age makes every comparison missing, and in DO IF a missing condition skips the whole structure, so the case never reaches ELSE (the new variable simply stays system-missing). Trapping MISSING(age) yourself makes that intent explicit and lets you assign a special code if you want one.

Python Stand-in: DO IF with a missing branch first

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.

Counting across variables

Transform > Count Values within Cases... counts how many of the selected variables hold certain values for each case. Example: how many of ten "yes/no" items a person answered "yes" (1).

TEXT
COUNT n_yes = q1 TO q10 (1).
COUNT n_missing = q1 TO q10 (MISSING).

COUNT never returns missing; it counts zero if nothing matches. In the dialog you set Define Values... (value, system-missing, range, etc.).

Strings and dates

TEXT
STRING fullname (A40).
COMPUTE fullname = CONCAT(RTRIM(first), ' ', RTRIM(last)).
COMPUTE initial = CHAR.SUBSTR(first, 1, 1).
COMPUTE birth_year = XDATE.YEAR(birthdate).
COMPUTE age_years = DATEDIFF($TIME, birthdate, 'years').

Declare string variables first with STRING name (An). where n is the length; strings shorter than the result are cut. Use RTRIM because string values can carry trailing spaces. $TIME is the current date and time, and $SYSMIS is the system-missing value. Dates need a Date type variable (see defining variables).

Python Stand-in: a total score with at least 80% answered

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.

Good practice

  • Write COMPUTE statements in syntax with comments explaining the logic.
  • Check the result: look at Frequencies, Descriptives and a few rows in Data View.
  • Give the new variable a label, a sensible type and (for categories) value labels.
  • Order matters: compute things before other things that use them.
  • Avoid overwriting an existing variable unless you intend to.

Common mistakes

  • Using + to add items and losing every case with one missing answer (or using SUM and counting cases that answered almost nothing).
  • Using ^ for a power instead of **.
  • Forgetting EXECUTE. and wondering why the variable is missing.
  • Writing IF (x = 1 OR 2) instead of IF (x = 1 OR x = 2) or ANY(x, 1, 2).
  • Dividing by zero or a missing value and getting system-missing without noticing.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A case has q1 = 4 and q2 missing. What does COMPUTE t = q1 + q2 give?

    Arithmetic with a missing operand returns system-missing. SUM(q1, q2) would give 4.
  2. 2. What does MEAN.3(a, b, c, d) return?

    The number after the dot is the minimum count of valid arguments required.
  3. 3. Which operator raises a number to a power in SPSS?

    SPSS uses ** for exponentiation.
  4. 4. In a DO IF structure, what happens to a case whose condition evaluates as missing?

    A missing logical result does not match any branch, so control passes to the command after END IF. Use MISSING(var) to handle those cases explicitly.

Summary

  • Compute Variable builds new variables from expressions; transformations stay pending until the next procedure or EXECUTE..
  • Arithmetic with a missing operand gives missing; SUM, MEAN and others ignore missing unless you add .n.
  • Use IF, DO IF and COUNT for conditional logic; comparisons return 1, 0 or missing.
  • Declare strings with STRING, and use date functions on Date variables.
  • Always label and check the new variable.

Next: Select, Split and Weight Cases