SAS Learning Post

Character to Numeric Conversion in SAS

How many of you have been given a SAS data set with variables such as Age, Height, and Weight and some or all of them were stored as character values instead of numeric? Probably EVERYONE! Yes, we all know how to do the old “swap and drop” (rename and convert), but wouldn’t it be nice to perform the conversion in one macro call?  You call the macro with the name of the original SAS data set that contains one or more variables you want to convert, the name of the SAS data set for the converted variables, and a list of character variables that need converting. Right after the macro listing, I’ll show you an example:

Here is a listing of the macro:

*Macro to convert selected character variables to numeric variables;
%macro char_to_num(In_dsn=, /*Name of the input data set*/
Out_dsn=, /*Name of the output data set*/
Var_list= /*List of character variables that you
want to convert from character to
numeric, separated by spaces*/);
/*Check for null var list */
%if &var_list ne %then %do;
/*Count the number of variables in the list */
%let n=%sysfunc(countw(&var_list));
data &Out_dsn;
set &In_dsn(rename=(
%do i = 1 %to &n;
/* break up list into variable names */
%let Var = %scan(&Var_list,&i);
/*Rename each variable name to C_ variable name */
&Var = C_&Var

%do i = 1 %to &n;
%let Var = %scan(&Var_list,&i);
&Var = input(C_&Var,best12.);
drop C_:;
%mend char_to_num;

As an example, the code below creates a SAS data set (Contains_Chars) followed by a call to the macro:

data Contains_Chars;
input Name $ Age $ Height $ Weight $;
Ron 55 72 180
Jane 57 63 101
Var_List=Age Height Weight)

The new data set Corrected has the same variable names as the character variables in the Contains_Chars data set except they are now all numeric variables. Here is a section from PROC CONTENTS:

Character to Numeric Conversion in SAS


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s