Check if vector of values exists in R column then return a single True value

Viewed 376

if I have this dataframe:

df <- tibble(code = c("ABC", "DEF", "GHI"))

and I have the following values:

my_values <- c("ABC","GHI") 

How can i check that my object my_values is found inside the dataframe df and return a single TRUE boolean value?

I do not care for how many times the values appear I just want to return a singular TRUE boolean if any or all of the values from my_values appears in the dataframe column called code?

My desired result is the single boolean TRUE - i'm stuck on this and have been using the %in% operator but to no avail.
4 Answers

How about

any(df$code %in% my_values) 

Or perhaps

any(my_values  %in% df$code) 
> TRUE %in% (my_values %in% df$code)
[1] TRUE

Basic R, no lib required

> stringr::str_detect(df, paste(my_values, collapse="|"))
[1] TRUE

If you want at least 1 of my_values in df$code to satisfy the test then:

result <- any(intersect(my_values, df$code))

Example:

x <- 1:3
y <- 2:4
z <- 5:7
any(intersect(x, y))
[1] TRUE
any(intersect(z, y))
[1] FALSE
Related