Often you may want to find the rows in a data frame whose value in a certain column matches some partial string.
Fortunately we can use the grep() function to do so, using the following syntax:
df[grep("string", df$column_name), ]
This tutorial provides several examples of how to use this function in practice on the following data frame:
#create data frame df frame(player=c('A', 'B', 'C', 'D', 'E', 'F', 'G'), position=c('S Guard', 'P Guard', 'P Guard', 'S Forward', 'P Forward', 'Center', 'Center'), points=c(28, 17, 19, 14, 23, 26, 5)) #view data frame df player position points 1 A S Guard 28 2 B P Guard 17 3 C P Guard 19 4 D S Forward 14 5 E P Forward 23 6 F Center 26 7 G Center 5
Example 1: Find Partial Match in a Specific Column
The following code shows how to find all rows in the data frame that contain the string ‘Gua’ in the position column:
df[grep("Gua", df$position), ] player position points 1 A S Guard 28 2 B P Guard 17 3 C P Guard 19
And the following code shows how to find all rows in the data frame that contain the string ‘P Gua’ in the position column:
df[grep("P Gua", df$position), ] player position points 2 B P Guard 17 3 C P Guard 19
Example 2: Find Several Partial Matches
The following code shows how to find all rows in the data frame that contain the string ‘S Gua’ or the string ‘Cen’ in the position column by using the | operator to indicate “or” in the grep argument:
df[grep("S Gua|Cen", df$position), ] player position points 1 A S Guard 28 6 F Center 26 7 G Center 5
Note that we can use the | operator to search for as many partial strings as we’d like.
The following code shows how to use this operator to return the rows with partial strings ‘A’, ‘C’, ‘D’, ‘F’, or ‘G’ in the player column:
df[grep("A|C|D|F|G", df$player), ] player position points 1 A S Guard 28 3 C P Guard 19 4 D S Forward 14 6 F Center 26 7 G Center 5
You can find more R tutorials on this page.