我一直在尝试用答案来回答其他类似的问题,但没有成功。我有两个数据集:
#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)这个运行,但是当我增加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"))发布于 2020-05-21 19:15:45
您可以使用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发布于 2020-05-21 19:08:45
这是一个结合了tidyr和Base R的答案。首先,我们读取数据:
text1 <- "Gene
ACE
BRCA
HER2"
text2 <- "Gene|interactors
GP5|ACE, NOS, C456
TP53|NOS, BRCA, NOTCH4"
df1 <- read.csv(text = text1,header = TRUE,stringsAsFactors = FALSE)
df2 <- read.csv(text = text2,header = TRUE,stringsAsFactors = FALSE,sep = "|")接下来,我们分离df2中的交互,并使用生成的向量在df1中创建逻辑变量。
df2 <- separate_rows(df2,interactors)
df1$matches <- ifelse(df1$Gene %in% df2$interactors,TRUE,FALSE)
df1对输出执行...and操作:
> df1
Gene matches
1 ACE TRUE
2 BRCA TRUE
3 HER2 FALSE
> 发布于 2020-05-21 19:19:23
使用基数R
genes <- df1$Gene
res <- genes %in% trimws(unlist(strsplit(df2$interactors, ",")))结果
> res
[1] TRUE TRUE FALSE可以使用以下命令将其添加到df1
df1$Matches <- reshttps://stackoverflow.com/questions/61932720
复制相似问题