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 here.
Additional Resources
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