首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >检查列表向量列中的成员资格

检查列表向量列中的成员资格
EN

Stack Overflow用户
提问于 2022-01-10 22:33:58
回答 4查看 102关注 0票数 5

假设我有一个data.frame,格式如下:

代码语言:javascript
运行
复制
Site     CowId    Result
FarmA    1000     c("Aerococcus viridans", "Staphylococcus chromogenes")
FarmA    1001     Staphylococcus aureus
FarmA    1002     Contaminated

我如何才能在不取消结果列内任何潜在向量嵌套的情况下,检查金黄色葡萄球菌色原是否是任何集合中的成员?

代码语言:javascript
运行
复制
df <- structure(list(Site = structure(c(1L, 1L, 1L), .Label = "FarmA", class = "factor"), CowId = 1000:1002, Result = list(c("Aerococcus viridans", "Staphylococcus chromogenes"), "Staphylococcus aureus", "Contaminated")), class = c("grouped_df", "tbl_df", "tbl", "data.frame"), row.names = c(NA, -3L), groups = structure(list( Site = structure(c(1L, 1L, 1L), .Label = "FarmA", class = "factor"), CowId = 1000:1002, .rows = structure(list(1L, 2L, 3L), ptype = integer(0), class = c("vctrs_list_of", "vctrs_vctr", "list"))), class = c("tbl_df", "tbl", "data.frame" ), row.names = c(NA, -3L), .drop = TRUE))
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2022-01-10 22:41:56

您可以使用/sapply来测试df$Result的所有成员上的字符串。

代码语言:javascript
运行
复制
testString <-"Staphylococcus chromogenes"
sapply(df$Result, function(results){testString %in% results})
#[1]  TRUE FALSE FALSE
票数 6
EN

Stack Overflow用户

发布于 2022-01-10 23:42:39

试试grepl + toString

代码语言:javascript
运行
复制
> grepl("Staphylococcus chromogenes", sapply(df$Result, toString), fixed = TRUE)
[1]  TRUE FALSE FALSE
票数 4
EN

Stack Overflow用户

发布于 2022-01-11 01:02:20

基于dplyr的另一种可能的解决方案

代码语言:javascript
运行
复制
library(dplyr)

df %>% 
  rowwise %>% 
  mutate(Presence = "Staphylococcus chromogenes" %in% Result)

#> # A tibble: 3 × 4
#> # Rowwise:  Site, CowId
#>   Site  CowId Result    Presence
#>   <fct> <int> <list>    <lgl>   
#> 1 FarmA  1000 <chr [2]> TRUE    
#> 2 FarmA  1001 <chr [1]> FALSE   
#> 3 FarmA  1002 <chr [1]> FALSE
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70659637

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档