Check if item is in list

Viewed 81

Suppose, I have a table in the following format:

CowId    Farm    Week1
1        CB      c("Staphylococcus aureus", "Escherichia coli")
2        CB      No Growth
3        CB      NA
4        CB      Staphylococcus aureus

How can I check if Staphylococcus aureus is a member of the Week1 column? I tried

dt.wide %>%
    filter(Week1 %in% "Staphylococcus aureus")

But it only captures CowId 4, not CowId 1. Any feedback would be helpful.

dt.wide <- structure(list(CowId = c(1L, 2L, 3L, 4L), 
                          Farm = structure(c(1L, 1L, 1L, 1L), 
                          .Label = c("CB", "CB", "CB", "CB"), 
                          class = "factor"), 
                          Week1 = list(c("Staphylococcus aureus", "Escherichia coli"), "No Growth", NA, "Staphylococcus aureus")), 
                          row.names = c(NA, -4L), 
                          class = c("tbl_df", "tbl", "data.frame"))
2 Answers

Base R approach :

subset(dt.wide, sapply(Week1, function(x) "Staphylococcus aureus" %in% x))

#   CowId Farm  Week1    
#  <int> <fct> <list>   
#1     1 CB    <chr [2]>
#2     4 CB    <chr [1]>

If you want to check if 'Staphylococcus aureus' is a member of the Week1 column without retaining what is inside the list. This approach will work.

You first unnest the column, apply your filters and if you want to, you can always nest again:

library(tidyr)
library(dplyr)

df %>% 
  unnest(Week1) %>% 
  filter(Week1 %in% "Staphylococcus aureus")
Related