How do you remove commas from a string in SAS?

In SAS, the TRANWRD function can be used to remove commas from a string. The TRANWRD function takes two parameters; the first parameter is the string that contains the comma, and the second parameter is the character or characters that should be removed from the string. The TRANWRD function then returns the string with the comma removed.


The easiest way to remove commas from a string in SAS is to use the TRANSLATE function, which converts every occurrence of one character to another character.

You can use the following basic syntax to do so:

data new_data;
    set original_data;
    string_var = compress(translate(string_var,"",','));
run;

This particular example removes every comma from each string in the string_var variable in a dataset.

The following example shows how to use this syntax in practice.

Example: Remove Commas from String in SAS

Suppose we have the following dataset in SAS that contains information about various basketball teams:

/*create dataset*/
data my_data;
    input team $ points;
    datalines;
,Mavs, 113
Pacers 95
,Ca,vs 120
Lakers 114
Heat 123
King,s 119
Raptors 105
,Hawks 95
Ma,gic 103
Spu,,rs 119
;
run;

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

Notice that several of the strings in the team column contain commas in various places.

We can use the following syntax to remove all commas from the strings in the team column:

/*create new dataset where commas are removed from each string in team column*/
data new_data;
    set my_data;
    team = compress(translate(team,"",','));
run;

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

Notice that the commas have been removed from each string in the team column.

Here is what this code actually did:

  • The TRANSLATE function replaced each comma with an empty space.
  • Then, the COMPRESS function removed the empty spaces from each string.

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

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

x