How to Use the TRANSLATE Function in SAS?

The TRANSLATE function in SAS is used to replace one or more characters in a string with other characters. It allows you to replace characters within a string using the FROM and TO parameters. The FROM parameter is a character to be replaced and the TO parameter is the character to replace it with. The TRANSLATE function is especially useful for cleaning up data or replacing special characters with standard characters.


You can use the TRANSLATE function in SAS to replace all occurrences of specific characters in a string with new characters.

This function uses the following syntax:

TRANSLATE(source, to, from)

where:

  • source: Name of the variable to search
  • to: Characters to use as replacement
  • from: Characters to replace

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

/*create dataset*/
data my_data;
    input team $ position $ points assists;
    datalines;
A Guard 14 4
A Guard 22 6
A Guard 24 9
A Forward 13 8
A Forward 13 9
A Guard 10 5
B Guard 24 4
B Guard 22 6
B Forward 34 2
B Forward 15 5
B Forward 23 5
B Guard 10 4
;
run;

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

Example 1: Use TRANSLATE to Replace Characters with New Characters

The following code shows how to use the TRANSLATE function to replace each occurrence of the letter “r” in the position column with a “z” instead:

/*create new dataset*/
data new_data;
    set original_data;
    position = translate(position, "z", "r");
run;

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

Notice that each occurrence of the letter “r”” in the position column has been replaced with the letter “z” instead.

Example 2: Use TRANSLATE to Replace Characters with Blanks

The following code shows how to use the TRANSLATE function to replace each occurrence of “r” in the position column with a blank instead:

/*create new dataset*/
data new_data;
    set my_data;
    position = compress(translate(position, "", "r"));
run;

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

This has the same effect as simply removing the string “r” from each position name.

Note #1: We wrapped the function around the TRANSLATE function to remove all blanks from the strings in the position column.

Note #2: You can find the complete documentation for the SAS TRANSLATE function .

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

x