SNT
SNT

Reputation: 1433

Check if value is in array of values in r dataframe

I have a dataframe with two columns Fruits and Groups . I want to check if the value in Fruits is the array in Groups. If yes then mutate a new field and add yes or no.

df <- data.frame(Fruits = c("Apple","Banana","Orange","Kiwi"),
                 Group = I(list(c("Apple","Strawberry"), 
                                c("Orange","Kiwi"),
                                c("Apple","Banana"),
                                c("Apple","Kiwi")
                                )))

df$Fruits %in% df$Group

Upvotes: 1

Views: 1144

Answers (2)

akrun
akrun

Reputation: 887831

We can use

library(data.table)
setDT(df)[, Present := unlist(Map(`%in%`, Fruits, Group))]

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 389235

As Group is a list we can't directly compare it. One way is to use mapply

df$Present <- c("No", "Yes")[mapply(`%in%`, df$Fruits, df$Group) + 1]

df
#  Fruits        Group Present
#1  Apple Apple, S....     Yes
#2 Banana Orange, Kiwi      No
#3 Orange Apple, B....      No
#4   Kiwi  Apple, Kiwi     Yes

mapply returns TRUE/FALSE values and then we use indexing technique to get Yes/No.

mapply(`%in%`, df$Fruits, df$Group)
#[1]  TRUE FALSE FALSE  TRUE

Or similarly with purrr map2_lgl

library(dplyr)
library(purrr)

df %>%
  mutate(Present = c("No", "Yes")[map2_lgl(Fruits, Group, `%in%`) + 1])

Upvotes: 3

Related Questions