【问题标题】:How to count how many times values appear in a dataframe per row in r?如何计算r中每行数据框中出现多少次值?
【发布时间】:2021-02-05 19:10:54
【问题描述】:

我有一个基因数据集,每个基因都与基因相互作用。我在这样的 2 列中有这个:

Gene    Interacting Genes
ACE     BRCA2, NOS2, SEPT9
HER2    AGT, TGRF
YUO     SEPT9, NOS2

另外,我有一个数据集,它只是一个基因列表。我希望在我的第二个数据集中创建一个count 列,其中每个基因有多少相互作用基因。我的第二个数据集看起来像:

Gene
NOS2
SEPT9
QRTY

此示例的输出如下所示:

Gene   Interacting Genes     Count
ACE     BRCA2, NOS2, SEPT9    2
HER2    AGT,   TGRF           0
YUO     SEPT9                 1

#NOS2 and SEPT9 are in the gene list dataframe and so are counted

我见过类似的问题,但不是每行在一个字符串中进行计数的问题,这是我坚持的部分。

输入数据:

#df1:
structure(list(Gene = c("ACE", "HER2", "YUO"), interactors = c("BRCA2, NOS2, SEPT9", 
"AGT,   TGRF", 
"SEPT9,  NOS2"
)), row.names = c(NA, -3L), class = c("data.table", "data.frame"
))

#df2:
structure(list(Gene = c("NOS2", "SEPT9", "QRTY")), row.names = c(NA, 
-3L), class = c("data.table", "data.frame"))

【问题讨论】:

    标签: r dataframe data.table


    【解决方案1】:

    您可以使用基于 dplyr 和 stringr 的解决方案。

    library(dplyr)
    library(stringr)
    
    df1 %>%
      mutate(count = str_count(interactors, str_c(df2$Gene, collapse = '|')))
    
    #   Gene        interactors count
    # 1  ACE BRCA2, NOS2, SEPT9     2
    # 2 HER2        AGT,   TGRF     0
    # 3  YUO       SEPT9,  NOS2     2
    

    【讨论】:

      【解决方案2】:

      使用 str_extract_all:

      > library(dplyr)
      > library(stringr)
      > df1 %>% mutate(counter = str_extract_all(interactors, paste0(df2$Gene, collapse = '|'))) %>% 
      +     rowwise() %>% mutate(count = length(counter)) %>% select(-counter)
      # A tibble: 3 x 3
      # Rowwise: 
        Gene  interactors        count
        <chr> <chr>              <int>
      1 ACE   BRCA2, NOS2, SEPT9     2
      2 HER2  AGT,   TGRF            0
      3 YUO   SEPT9,  NOS2           2
      > 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-23
        • 1970-01-01
        • 2016-10-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多