SAS: How to Change Length of Character Variables


The easiest way to change the length of character variables in SAS is to use the ALTER TABLE and MODIFY statements within PROC SQL.

You can use the following basic syntax to do so:

proc sql;
    alter table my_data
    modify team char(4);
quit;

This particular example modifies the length of the character variable called team in the dataset called my_data to have a length of 4.

The following example shows how to use this syntax in practice.

Example: Change Length of Character Variable in SAS

Suppose we have the following dataset in SAS that contains information about various basketball teams:

/*create dataset*/
data my_data;
    input team $ points;
    datalines;
Cavs 12
Cavs 24
Heat 15
Cavs 26
Heat 14
Mavs 36
Mavs 19
Nets 20
Nets 31
;
run;

/*view dataset*/
proc print data=my_data;

We can use PROC CONTENTS to view the length of each variable in the dataset:

/*view length of each variable in dataset*/
proc contents data=my_data;

The last table in the output shows the length of each variable:

From this table we can see:

  • The points variable is a numeric variable with a length of 8.
  • The team variable is a character variable with a length of 8.

Suppose we would like to change the team variable to have a length of 4.

We can use the following syntax to do so:

/*change length of team variable to 4*/
proc sql;
    alter table my_data
    modify team char(4);
quit;

We can use them use PROC CONTENTS once again to view the length of each variable in the dataset:

/*view updated length of each variable in dataset*/
proc contents data=my_data;

The last table in the output shows the length of each variable:

We can see that the team variable now has a length of 4.

It’s worth noting that none of the values in the team column were truncated because the longest team name had a length of 4.

However, if you changed the length of the team variable to 3, for example, then the last character of some team names would have been truncated.

Using this method, no warning message will appear if truncation occurs so make sure you know the maximum length of strings in your character column before you use this method.

Additional Resources

The following tutorials explain how to perform other common tasks in SAS:

How to Extract Numbers from String in SAS
How to Use the SUBSTR Function in SAS
How to Remove Special Characters from Strings in SAS

Featured Posts

Leave a Reply

Your email address will not be published. Required fields are marked *