How to use str_detect with multiple words


I want to remove few rows that contain different words. For example, variable Country has several countries in it and I want to exclude the rows with Mexico and Cambodia. I was trying to do something like this:
df <- df %>%
filter(str_detect(Country, "Mexico", "Cambodia", negate = TRUE))

How can I remove rows with specific words in it?


In a regular expression, | means OR.


DF <- data.frame(Country = c("Austria", "Cambodia", "Congo", "Mexico", "Nepal"))
#>    Country
#> 1  Austria
#> 2 Cambodia
#> 3    Congo
#> 4   Mexico
#> 5    Nepal
DF <- DF %>%
  filter(str_detect(Country, "Mexico|Cambodia", negate = TRUE))
#>   Country
#> 1 Austria
#> 2   Congo
#> 3   Nepal

Created on 2020-06-15 by the reprex package (v0.3.0)

Thanks @FJCC! Why didn't I think about including OR? Anyhow, it seems like str_detect doesn't work right for me for some reason. Here is my code and Error:

Thanks for your help!

Do not put quotes around each country name. Put quotes around the entire regular expression.
Not this


Use this


Perfect! It works...Thank you!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.