r - 如何识别数据集之间的匹配字符串?
问题描述
我一直在尝试使用其他类似问题的答案,但没有运气。我有 2 个数据集:
#df1:
Gene
ACE
BRCA
HER2
#df2:
Gene interactors
GP5 ACE, NOS, C456
TP53 NOS, BRCA, NOTCH4
我希望在我的第一个数据集中添加一列,以识别在我的第二个数据集中显示为交互器的基因。
输出:
#df1:
Gene Matches
ACE TRUE
BRCA TRUE
HER2 FALSE
目前我正在尝试df1$Matches <- mapply(grepl, df1$Gene, df2$interactors)
This runs 但是当我增加 df1 中的基因数量时,匹配的数量会下降,这没有意义,因为我没有删除最初运行的任何基因,让我认为这不起作用就像我期望的那样。
我也试过:
library(stringr)
df1 %>%
+ rowwise() %>%
+ mutate(exists_in_title = str_detect(Gene, df2$interactors))
Error: Column `exists_in_title` must be length 1 (the group size), not 3654
In addition: There were 50 or more warnings (use warnings() to see the first 50)
我也尝试过同样错误的 dplyr 版本。
我还有什么其他方法可以解决这个问题?任何帮助,将不胜感激。
输入数据:
dput(df1)
structure(list(Gene = c("ACE", "BRCA", "HER2")), row.names = c(NA,
-3L), class = c("data.table", "data.frame"))
dput(df2)
structure(list(Gene = c("GP5", "TP53"), interactors = c("ACE, NOS, C456",
"NOS, BRCA, NOTCH4")), row.names = c(NA, -2L), class = c("data.table",
"data.frame"))
解决方案
您可以拆分使用 strsplit
library(dplyr)
df1$Matches <- df1$Gene %in% trimws(unlist(strsplit(df2$interactors, ",")))
> df1
Gene Matches
1 ACE TRUE
2 BRCA TRUE
3 HER2 FALSE
推荐阅读
- visual-studio-2017 - 安装 ML.NET 模型生成器包时遇到问题
- reactjs - 像亚马逊一样具有放大效果的 React 图像库
- php - 如何在 cakephp 页面重新加载之前触发事件,或者只是简单的 php 跨平台兼容方法?
- facebook - api 提供者会知道请求是来自 facebook 应用还是网站?
- winapi - 如何将编辑框转换为数字程序集?
- sql - 将源与目标中的最新记录进行比较
- r - 如何添加图例以识别 ggplot 中的垂直线?
- python - 如何在 Sentry Python SDK 中定义日志记录级别
- python - tkinter 小部件上的空间显示问题
- javascript - Javascript计算div元素中不同字符串的平均值,只有一个类而不改变html