Home » SAS: Filter for Rows that Contain String

SAS: Filter for Rows that Contain String

by Erma Khan

You can use the following methods to filter SAS datasets for rows that contain certain strings:

Method 1: Filter Rows that Contain Specific String

/*filter rows where var1 contains "string1"*/
data specific_data;
    set original_data;
    where var1 contains 'string1';
run;

Method 2: Filter Row that Contain One of Several Strings

/*filter rows where var1 contains "string1", "string2", or "string3"*/
data specific_data;
    set original_data;
    where var1 in ('string1', 'string2', 'string3');
run;

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

/*create dataset*/
data nba_data;
    input team $ points;
    datalines;
Mavs 95
Spurs 99
Warriors 104
Rockets 98
Heat 95
Nets 90
Magic 99
Cavs 106
;
run;

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

Method 1: Filter Rows that Contain Specific String

The following code shows how to filter the dataset for rows that contain the string “avs” in the team column:

/*filter rows where team contains the string 'avs'*/
data specific_data;
    set nba_data;
    where team contains 'avs';
run;

/*view resulting rows*/
proc print data=specific_data;

The only two rows shown are the ones where the team column contains ‘avs’ in the name.

Method 2: Filter Rows that Contain One of Several Strings

The following code shows how to filter the dataset for rows that contain the strings “Mavs”, “Nets”, or “Rockets” in the team column:

/*filter rows where team contains the string 'Mavs', 'Nets', or 'Rockets'*/
data specific_data;
    set nba_data;
    where team in ('Mavs', 'Nets', 'Rockets');
run;

/*view resulting rows*/
proc print data=specific_data;

The resulting dataset only shows the rows where the team column contains one of the three strings that we specified.

Additional Resources

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

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

Related Posts