R 检查项目是否在列表中
假设我有一个以下格式的表:R 检查项目是否在列表中,r,dplyr,R,Dplyr,假设我有一个以下格式的表: CowId Farm Week1 1 CB c("Staphylococcus aureus", "Escherichia coli") 2 CB No Growth 3 CB NA 4 CB Staphylococcus aureus 我如何检查金黄色葡萄球菌是否是Week1专栏的成员?我试过了 dt.wide %&g
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"))
dt.wide如果您想检查“金黄色葡萄球菌”是否是Week1列的成员,而不保留列表中的内容。这种方法会奏效
首先unnest
列,应用过滤器,如果愿意,可以随时再次嵌套:
library(tidyr)
library(dplyr)
df %>%
unnest(Week1) %>%
filter(Week1 %in% "Staphylococcus aureus")
基本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]>
子集(dt.wide,sapply(1周,函数(x)“金黄色葡萄球菌”%in%x))
#科维德农场周1
#
#1 1 CB
#2.4 CB
您能否以dput
格式发布样本数据?请使用dput(dt.wide)
的输出编辑问题。或者,如果它的输出太大,dput(head(dt.wide,20))
@RuiBarradas当然是。有趣的是,我不知道这个函数。谢谢你的建议。