0

我有一个基因数据集和每个基因相互作用的基因。我在这样的 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"))
4

2 回答 2

2

您可以使用基于 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
于 2020-10-22T18:02:01.660 回答
0

使用 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
> 
于 2020-10-22T18:02:44.430 回答