How to delete rows of R dataframe based on string match?

In this article, we will discuss how to delete rows of a dataframe based on string match in R Programming Language.

For this grep() function can be used. This function searches for matches of certain character patterns in a vector of character strings and returns a boolean value as TRUE if that string is present else it returns FALSE.

Syntax: grepl(pattern, string, ignore.case=FALSE)

Parameter:

  • pattern: regular expressions pattern
  • string: character vector to be searched

First with the help of grepl() we have obtained the rows which consist of specified substrings in it. Then with Not operator(!) we have removed those rows in our data frame and stored them in another data frame.

Data frame in use:

Data frame

Example 1:

R




Strings<-c("Beginner","For","Beginner","GFG","Ram",
           "Ramesh","Gene","Siri")
Id<-1:8
 
# df is our data frame name
df<-data.frame(Id,Strings)  
 
print(df)
 
# Removes the rows in Data frame
# which consist "Ra" in it
new_df=df[!grepl("Ra",df$Strings),]
print(new_df)


Output:

Example 2:

R




Strings<-c("Beginner","For","Beginner","GFG","Ram",
           "Ramesh","Gene","Siri")
Id<-1:8
 
# df is our data frame name
df<-data.frame(Id,Strings)  
 
print(df)
 
# Removes the rows in Data frame
# which consist "Ge" in it
new_df=df[!grepl("Ge",df$Strings),]
print(new_df)


Output: