SPSS: Select Cases if String Contains Specific Text


Often you may want to select cases that contain specific text in SPSS.

Fortunately this is easy to do by using the char.index function in the Select Cases dialogue box.

The following example shows how to do so in practice.

Example: Select Cases if String Contains Specific Text

Suppose we have the following dataset in SPSS that contains information about points scored by basketball players on various teams:

Suppose that we would like to select all cases that contain the string “avs” in the name of the Team column.

To do so, click the Data tab and then click Select Cases:

In the new window that appears, click the button next to If condition is satisfied, then click the If button:

In the new window that appears, type the following formula into the dialogue box:

char.index(Team,"avs")>0

Then click Continue. Then click OK.

All of the cases that do not contain “avs” in the Team column will be crossed out:

Also note that a new column named filter_$ has been created that contains a value of 1 for cases that meet the criteria we specified and a value of 0 for cases that didn’t meet the criteria.

How This Formula Works

Recall the formula that we typed into the dialogue box to check if each string in the Team column contained the string “avs” or not:

char.index(Team,"avs")>0

This formula uses the char.index function to return the position in the string of the Team column where the substring “avs” is first detected.

If the substring “avs” is not detected in the string, then the char.index function simply returns 0.

We then check if the value returned by char.index is greater than 0.

For cases that contain “avs” in the Team column, this formula will return True.

For cases that do not contain “avs” in the Team column, this formula will return False.

Additional Resources

The following tutorials explain how to perform other common operations in SPSS:

How to Select Cases Based on Multiple Conditions in SPSS
How to Recode Variables in SPSS
How to Replace Missing Values with Zero in SPSS

Leave a Reply

Your email address will not be published. Required fields are marked *