Search code examples
rsearchvectornested

Check if a value from one column is present inside a list in a different column


In a dataframe I would like to test if a value in a column is present in a second column. However, the second column is a list column containing a repeated vector as shown below:

library(tidyverse)

numbers.col <- c(1,2,3)

letters.col <- c("a", "b", "c")

search.for <- list("a","b")

df <- data.frame(numbers.col, letters.col)

df$search.for <- list(search.for)

df

This results in:

  numbers.col letters.col search.for
1           1           a       a, b
2           2           b       a, b
3           3           c       a, b

Trying to search. If it worked, I would have "Ok" for rows 1 and 2 and "Nok" for row 3 (result column).

mutate(df, result = if_else(df$letters.col %in% df$search.for, "Ok", "Nok"))

  numbers.col letters.col search.for result
1           1           a       a, b    Nok
2           2           b       a, b    Nok
3           3           c       a, b    Nok

Is there a way to make it work?


Solution

  • You just need to use map2_chr to map the two vectors to a string:

    library(tidyverse)
    
    df |>
      mutate(result = map2_chr(letters.col, search.for, 
                               ~if_else(.x %in% .y, "Ok", "Nok")))
    #>   numbers.col letters.col search.for result
    #> 1           1           a       a, b     Ok
    #> 2           2           b       a, b     Ok
    #> 3           3           c       a, b    Nok