In this tutorial, we will show how to use the TRANWRD and TRANSLATE functions in SAS, along with examples.
Difference between TRANWRD and TRANSLATE Functions
The TRANWRD replaces specific words within a character string with other words, whereas the TRANSLATE function replaces specific characters within a character string with other characters.
To remember the TRANWRD function, you can focus on the last three characters "WRD" which can stand for "Word Replacement"
Syntax of TRANWRD and TRANSLATE Functions
TRANWRD
The syntax of the TRANWRD Function in SAS is as follows:
TRANWRD(string, find_what , replace_with)
TRANSLATE
Below is the syntax of TRANSLATE Function in SAS.
TRANSLATE(string, replace_with, find_what)
string
: The character variable or string.find_what
: The character or word to be replaced within the string.replace_with
: The character or word that will replace the old word within the string.
Let's create a sample dataset for demonstration purpose.
data have; input phrase $45.; cards; Hello, How are you doing? The brown cat jumps over the hairy dog XYYXYYY ; run;
Here we are replacing characters XY
with AB
in the character variable named "phrase".
data want; set have; phrase_tranwrd = tranwrd(phrase, "XY", "AB"); phrase_translate = translate(phrase, "AB", "XY"); run;
"XYYXYYY" becomes "ABYABYY" because TRANWRD replaces the pattern "XY" with "AB" whereas TRANSLATE returns ABBABBB as it replaces each occurrence of "X" with "A" and each occurence of "Y" with "B".
In this example, we are going to replace the word Hello
with Hey
.
data want; set have; new_phrase = tranwrd(phrase, "Hello", "Hey"); new_phrase2= translate(phrase, "Hey", "Hello"); run;
When we used the TRANSLATE function with the input string "Hello, How are you doing?" and replaced "Hello" with "Hey", the resulting string is "Heyy , H w are y u d ing?".
Since the TRANSLATE function replaces individual characters, it doesn't recognize the entire "Hello" and "Hey" as a single unit. Instead, it replaces each occurrence of "H" with "H", "e" with "e", and "l" with "y" and "o" with blank.
Share Share Tweet