1

How do I remove all rows from a data frame that contain any of the values I assign in a string vector? I've tried grepl, but that only seems to work when one word is concerned.

number <- c(1:5)
text <- c("First text","Second text","Another text here","Yet another one","Last text")
example <- as.data.frame(cbind(number,text))

  number              text
1      1        First text
2      2       Second text
3      3 Another text here
4      4   Yet another one
5      5         Last text

Doesn't work:

remove <- c("First","Yet")
example[!grepl(remove,example$text),]

Desired outcome:

 number              text
1      2       Second text
2      3 Another text here
3      5         Last text

1 Answers1

2

We can paste the elements in 'remove' to a single string separated by | (which means OR) and feed it as pattern in grepl for the 'text' column, negate the logical vector and then subset the rows of 'example

 example[!grepl(paste(remove, collapse="|"), example$text),]
 # number              text
 #2      2       Second text
 #3      3 Another text here
 #5      5         Last text
akrun
  • 874,273
  • 37
  • 540
  • 662