【问题标题】:How to identify matching strings between datasets?如何识别数据集之间的匹配字符串?
【发布时间】:2020-05-21 10:45:25
【问题描述】:

我一直在尝试使用其他类似问题的答案,但没有运气。我有 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) 这会运行,但是当我增加 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"))

【问题讨论】:

    标签: r dplyr stringr


    【解决方案1】:

    你可以使用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
    

    【讨论】:

      【解决方案2】:

      这是一个结合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
      

      ...和输出:

      > df1
        Gene     matches
      1  ACE        TRUE
      2 BRCA        TRUE
      3 HER2       FALSE
      > 
      

      【讨论】:

        【解决方案3】:

        有基础R

        genes <- df1$Gene
        res <- genes %in% trimws(unlist(strsplit(df2$interactors, ",")))
        

        结果

        > res
        [1]  TRUE  TRUE FALSE
        

        可以添加到 df1 上

        df1$Matches <- res
        

        【讨论】:

        • 这不是“使用 Base-R”
        猜你喜欢
        • 1970-01-01
        • 2011-10-30
        • 2019-10-16
        • 2011-05-06
        • 2020-07-30
        • 2016-02-19
        • 2018-02-23
        • 2017-04-02
        • 1970-01-01
        相关资源
        最近更新 更多