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)
- 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;
Notice that each occurrence of “r” in the position column has been replaced with a blank instead.
This has the same effect as simply removing the string “r” from each position name.
Note #1: We wrapped the COMPRESS 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 here.
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