How do I delete a row with a pattern in R?

Viewed 589

I have a dataframe where I want to delete all rows with specific pattern. I am confused with compiling a regular expression.

Data:

structure(list(id = 1:5, email = c("1@gmail.com", "2@gmail.com", 
"3@gmail.com", "4@pattern.com", "5@pattern.com")), class = "data.frame", row.names = c(NA, 
-5L))

What I am trying to do is:

data <- data %>%
  filter(email != ".+@pattern.com")

But something is wrong with my regex. What is the most effective way to compose a regular expression for such patterns? What is the proper regex pattern for my sample case?

2 Answers

This uses grepl to perform a regex comparison

libary(dplyr)

data %>%
  filter(!grepl("@pattern.com$", email))

  id       email
1  1 1@gmail.com
2  2 2@gmail.com
3  3 3@gmail.com

In base R you can remove the rows in which the pattern @pattern.com is detected by the function greplin the email column:

data[-which(grepl("@pattern.com", data$email)),]
  id       email
1  1 1@gmail.com
2  2 2@gmail.com
3  3 3@gmail.com

Data:

data <- structure(list(id = 1:5, email = c("1@gmail.com", "2@gmail.com", 
                                           "3@gmail.com", "4@pattern.com", "5@pattern.com")), class = "data.frame", row.names = c(NA, 
Related