Converting a character (or string) variable to a numeric variable and vice versa in SAS and SPSS (syntax)

Converting a character (or string) variable to numeric variable and vice versa in SAS and SPSS (syntax)


We will discuss two scenarios. First is where our variable is a Character (in SAS) or a String variable (in SPSS), which may contain numerals, letters, or any other special characters), but should be converted to a Numeric variable.


Here I created in SAS a Character variable which contains only letters, and there are only three letters in each record, as the informat indicates.

data test;
input character$3.;


And here is a program for creating the same dataset using SPSS syntax


data list list / id * character (A3).
begin data
1 "abc"
2 "bcd"
3 "cde"
end data.


Converting this Character variable to a Numeric variable can be easily done in SAS with the IF-THEN statement, as can be seen here where I created a new Numeric variable ‘characterB’. 


data work.Test;
set work.Test;
If character='abc' THEN characterB=123;
If character='bcd' THEN characterB=234;
If character='cde' THEN characterB=345;


With the new variable of ‘characterB’ containing only numbers, SAS automatically classified it as a Numeric variable.


As we have only a few values, the Recode command using SPSS syntax can be done with one of the two following options:


recode character ('abc' = 123) ('bcd' = 234) ('cde' = 345) 
into CharacterB.


compute characterB= 0.
if character = 'abc' characterB = 123.
if character = 'bcd' characterB = 234.
if character = 'cde' characterB = 345.


The second scenario is where a variable contains only numbers, but was classified as a Character or String variable. Swapping the informat from a Character variable to a Numeric Variable can be done in SAS with the following INPUT function:


data work.Test;
set work.Test;
numeric=input(character, best3.);


This will create a new Numeric variable with identical content, but with a different informat.



Similar results can be achieved in SPSS with the RECODE command and the CONVERT INTO option


recode character (convert) into numeric.



Converting the inforamt from a Numeric variable to a Character variable can be done in SAS with the following PUT statement:


data work.Test;
set work.Test;


Similarly this will create a new Character variable with identical content, but with a different informat.


SPSS users can use, again, the RECODE command, with CONVERT INTO option.


recode numeric (convert) into character.


Further reading:

Ronald Cody (n.d.) An Introduction to SAS® Character Functions

* Christopher J. Bost (n.d.) Automatically Converting Character Variables That Store Numbers to Numeric Variables


Questions? Comments? Drop us a line..