SAS: TRANWRD and TRANSLATE Functions (with Examples)

Deepanshu Bhalla Add Comment

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.
Sample Dataset

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;
SAS: TRANWRD and TRANSLATE Functions

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;
TRANWRD vs TRANSLATE

"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".

How to replace words in SAS?

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;
replace words in SAS

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.

Related Posts
Spread the Word!
Share
About Author:
Deepanshu Bhalla

Deepanshu founded ListenData with a simple objective - Make analytics easy to understand and follow. He has over 10 years of experience in data science. During his tenure, he worked with global clients in various domains like Banking, Insurance, Private Equity, Telecom and HR.

Post Comment 0 Response to "SAS: TRANWRD and TRANSLATE Functions (with Examples)"
Next → ← Prev