Beans On Toast
Beans On Toast

Reputation: 1081

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

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.

Upvotes: 2

Views: 1225

Answers (4)

SteveM
SteveM

Reputation: 2301

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

Upvotes: 1

Necklondon
Necklondon

Reputation: 998

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

Basic R, no lib required

Upvotes: 3

AnilGoyal
AnilGoyal

Reputation: 26218

How about

any(df$code %in% my_values) 

Or perhaps

any(my_values  %in% df$code) 

Upvotes: 3

user438383
user438383

Reputation: 6206

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

Upvotes: 2

Related Questions