How to Use the TRANWRD Function in SAS (With Examples)


You can use the TRANWRD function in SAS to find and replace all occurrences of a specific pattern of characters in a string.

This function uses the following syntax:

TRANWRD(source, target, replacement)

where:

  • source: Name of the variable to search
  • target: Character pattern to search for
  • replacement: Character pattern to use for replacing target

The following examples show how to use this function in practice with the following dataset in SAS:

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

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

Example 1: Use TRANWRD to Replace Characters with New Characters

The following code shows how to use the TRANWRD function to replace each occurrence of “Fast” in the team column with the string “Slow” instead:

/*create new dataset*/
data new_data;
    set original_data;
    team = tranwrd(team, "Fast", "Slow");
run;

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

Notice that each occurrence of “Fast” in the team names have been replaced with “Slow” instead.

Example 2: Use TRANWRD to Replace Characters with Blanks

The following code shows how to use the TRANWRD function to replace each occurrence of “Fast” in the team column with a blank instead:

/*create new dataset*/
data new_data;
    set original_data;
    team = tranwrd(team, "Fast", "");
run;

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

Notice that each occurrence of “Fast” in the team names have been replaced with a blank instead.

This has the same effect as simply removing the string “Fast” from each team name.

Note: You can find the complete documentation for the SAS TRANWRD function here.

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

Leave a Reply

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