18.8 C
London
Monday, June 2, 2025
HomeSASData Munging in SASHow to Replace Characters in a String in SAS (With Examples)

How to Replace Characters in a String in SAS (With Examples)

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

You can use the tranwrd() function to replace characters in a string in SAS.

Here are the two most common ways to use this function:

Method 1: Replace Characters in String with New Characters

data new_data;
    set original_data;
    new_variable = tranwrd(old_variable, "OldString", "NewString");
run;

Method 2: Replace Characters in String with Blanks

data new_data;
    set original_data;
    new_variable = tranwrd(old_variable, "OldString", "");
run;

The following examples show how to use each method with the following dataset in SAS:

/*create dataset*/
data original_data;
    input team $1-20;
    datalines;
Angry Bees
Angry Hornets
Wild Mustangs
Kind Panthers
Kind Cobras
Wild Cheetahs
Wild Aardvarks
;
run;

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

Example 1: Replace Characters in String with New Characters

The following code shows how to replace the word “Wild” in the team variable with the word “Fast”:

/*replace "Wild" with "Fast" in team variable*/
data new_data;
    set original_data;
    new_team = tranwrd(team, "Wild", "Fast");
run;

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

Notice that each team that had “Wild” in the name now has the word “Fast” in the name instead.

Any team that did not have “Wild” in the name simply kept their original name.

Example 2: Replace Characters in String with Blanks

The following code shows how to replace the word “Wild” in the team variable with a blank:

/*replace "Wild" with a blank in team variable*/
data new_data;
    set original_data;
    new_team = tranwrd(team, "Wild", "");
run;

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

Notice that any team that had “Wild” in the name simply had the word “Wild” replaced with a blank.

Additional Resources

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

How to Normalize Data in SAS
How to Replace Missing Values with Zero in SAS
How to Remove Duplicates in SAS

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories