SPSS tutorials

BASICS DATA ANALYSIS T-TEST ANOVA CHI-SQUARE TEST

SPSS LOOP – Quick Tutorial & Examples

LOOP is a command for running one or many SPSS transformation commands repetitively. SPSS LOOP is often used together with VECTOR. An (often) easier alternative is DO REPEAT.

Example: Replacing Double by Single Spaces

*Create mini test dataset.

data list free/sentence(a45).
begin data
'a b c d    e     f     g     h        i'
end data.

SPSS LOOP - Minimal Specification

SPSS LOOP Syntax Example 1

*Wrong way (triggers warning #534) to replace double spaces by single ones.

loop.
compute sentence = replace(sentence,'  ',' ').
end loop.
execute.

The LOOP Index Variable

SPSS LOOP Syntax Example 2

*Replace double spaces by single ones exactly three times.

loop repetition = 1 to 3.
compute sentence = replace(sentence,'  ',' ').
end loop.
execute.

LOOP Index as Scratch Variable

SPSS LOOP Syntax Example 3

*Replace double spaces by single ones exactly three times.

loop # = 1 to 3.
compute sentence = replace(sentence,' ',' ').
end loop.
exe.

END LOOP IF

SPSS LOOP Syntax Example 4

*Stop looping when double spaces aren't present anymore.

loop.
compute sentence = replace(sentence,' ',' ').
end loop if char.index(sentence,' ') = 0.
exe.

LOOP IF

SPSS LOOP Syntax Example 5

*Start an iteration if a double space is present.

loop if char.index(sentence,' ') > 0.
compute sentence = replace(sentence,' ',' ').
end loop.
exe.

Using the LOOP Index

SPSS LOOP Syntax Example 6

*1. Create mini test dataset.

data list free/name(a10).
begin data
Anneke Martin Stefan
end data.

*2. Count occurrence of 'e' by looping through letters in name.

compute count_e = 0.
loop # = 1 to char.length(name).
if char.substr(name,#,1) = 'e' count_e = count_e + 1.
end loop.
exe.

The BY Keyword

SPSS LOOP Syntax Example 7

*1. Create mini test dataset.

data list free/v1 to v12 (12f1.0).
begin data
0 0 0 0 0 1 0 1 1 1 1 1
end data.

*2. Compute 4 sums, each over 3 adjacent variables.

vector v = v1 to v12 / s(4).
loop # = 3 to 12 by 3.
compute s(# / 3) = sum(v(#),v(# - 1),v(# - 2)).
end loop.
exe.

Previous tutorial: SPSS DO REPEAT – Simple Tutorial & Examples

Next tutorial: SPSS VECTOR – Quick Tutorial

Let me know what you think!

*Required field. Your comment will show up after approval from a moderator.

This tutorial has 19 comments