Skip to Main Content

Converting string variables to numeric | SPSS Code Fragments

This shows how to convert a string variable race to a numeric variable
racen using two methods, the first a bit simpler but more cumbersome, the
second method more streamlined but a bit trickier.

DATA LIST FREE / race (A10).
BEGIN DATA.
white
black
asian
hispanic
white
END DATA.

LIST CASES.

* make string to numeric, method 1 .
IF (race="white") racen=1.
IF (race="asian") racen=2.
IF (race="hispanic") racen=3.
IF (race="black") racen=4.

CROSSTAB /TABLES=race BY racen.

* make string to numeric, method 2 .
DO REPEAT A="white" "asian" "hispanic" "black" /B=1 2 3 4.
IF (race=A) racen=B.
END REPEAT print.
execute.

CROSSTAB /TABLES=race BY racen.