Home » How to Replace Characters in a String in SAS (With Examples)

How to Replace Characters in a String in SAS (With Examples)

by Tutor Aspire

You can use the tranwrd() function to replace characters in a string in SAS.

Here are the two most common ways to use this function:

Method 1: Replace Characters in String with New Characters

data new_data;
    set original_data;
    new_variable = tranwrd(old_variable, "OldString", "NewString");
run;

Method 2: Replace Characters in String with Blanks

data new_data;
    set original_data;
    new_variable = tranwrd(old_variable, "OldString", "");
run;

The following examples show how to use each method with the following dataset in SAS:

/*create dataset*/
data original_data;
    input team $1-20;
    datalines;
Angry Bees
Angry Hornets
Wild Mustangs
Kind Panthers
Kind Cobras
Wild Cheetahs
Wild Aardvarks
;
run;

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

Example 1: Replace Characters in String with New Characters

The following code shows how to replace the word “Wild” in the team variable with the word “Fast”:

/*replace "Wild" with "Fast" in team variable*/
data new_data;
    set original_data;
    new_team = tranwrd(team, "Wild", "Fast");
run;

/*view new dataset*/
proc print data=new_data;

Notice that each team that had “Wild” in the name now has the word “Fast” in the name instead.

Any team that did not have “Wild” in the name simply kept their original name.

Example 2: Replace Characters in String with Blanks

The following code shows how to replace the word “Wild” in the team variable with a blank:

/*replace "Wild" with a blank in team variable*/
data new_data;
    set original_data;
    new_team = tranwrd(team, "Wild", "");
run;

/*view new dataset*/
proc print data=new_data;

Notice that any team that had “Wild” in the name simply had the word “Wild” replaced with a blank.

Additional Resources

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

How to Normalize Data in SAS
How to Replace Missing Values with Zero in SAS
How to Remove Duplicates in SAS

You may also like