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

The TRANWRD function in SAS is used to replace a specified word or character string with a new word or character string in a text string. The TRANWRD function has the syntax TRANWRD(string, old, new) where string is the text string, old is the word or character string to be replaced and new is the replacement word or character string. Examples of the TRANWRD function can be used to replace words in a string, replace characters in a string, and to replace multiple words in a string.


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;

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 .

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

x