假设我有一个格式如下的表格:
CowId Farm Week1
1 CB c("Staphylococcus aureus", "Escherichia coli")
2 CB No Growth
3 CB NA
4 CB Staphylococcus aureus
如何查看金黄色葡萄球菌是否为 Week1 列的成员?我试过了
dt.wide %>%
filter(Week1 %in% "Staphylococcus aureus")
但它只捕获 CowId 4,而不捕获 CowId 1。任何反馈都会有所帮助。
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"))
答案 0 :(得分:2)
基础 R 方法:
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]>
答案 1 :(得分:1)
如果您想检查 'Staphylococcus aureus' 是否是 Week1 列的成员而不保留列表中的内容。这种方法会奏效。
您首先unnest
列,应用您的过滤器,如果您愿意,您可以随时再次嵌套:
library(tidyr)
library(dplyr)
df %>%
unnest(Week1) %>%
filter(Week1 %in% "Staphylococcus aureus")