首页 > 解决方案 > 如何创建一个值依赖于 r 中其他列的列?

问题描述

我有一个临床试验数据集,我希望为它创建一列基因——与它们出现的临床试验相匹配的基因。

我的数据集如下所示:

Study ID   Title                             Drug        
1         Study of placement              BRCA2-drug
2         Study of ACE                    Gene1-drug
3         Another ACE study               Gene2-drug
4         Study of NOS3 and ACE            ACE-drug

(请注意,在我的真实数据中,我有更多列可以出现基因名称)

然后我有一个基因列表:

Gene
ACE
BRCA2
NOS3
HER2

我希望在我的第一个数据集匹配基因中创建一个列来研究,例如输出:

Gene      Study ID      Title                             Drug        
BRCA2         1         Study of placement              BRCA2-drug
ACE           2         Study of ACE                    Gene1-drug
ACE           3         Another ACE study               Gene2-drug  
ACE, NOS3     4         Study of NOS3 and ACE            ACE-drug

我不知道从哪里开始,特别是制作一个列,如果该行中出现多个基因,该列还允许该行包含多个基因。我一直在尝试使用dplyr::group_by(),但还没有走远。

输入数据:

#Clinical trials data:
structure(list(StudyID = 1:4, Title = c("Study of placement", 
"Study of ACE", "Another ACE study", "Study of NOS3 and ACE"), Drug = c("BRCA2-drug", 
"Gene1-drug", "Gene2-drug","ACE-drug")), row.names = c(NA, -4L), class = c("data.table", 
"data.frame"))

#Gene list:
structure(list(Gene = c("ACE", "NOS3", "HER2", "BRCA1")), row.names = c(NA, 
-4L), class = c("data.table", "data.frame"))

标签: r

解决方案


您可以创建一个将所有基因组合在一起的模式。从多列中提取存在的基因并将它们组合成一列。

library(dplyr)
pat <-  paste0(gene_list$Gene, collapse = '|')

trials %>%
  mutate(across(.fns = ~str_extract_all(., pat), .names = '{col}_new')) %>% 
  rowwise() %>%
  mutate(Gene = toString(unique(unlist(c_across(ends_with('_new')))))) %>%
  select(-ends_with('new'))

#   StudyID Title                 Drug       Gene     
#    <int> <chr>                 <chr>      <chr>    
#1       1 Study of placement    BRCA2-drug BRCA2    
#2       2 Study of ACE          Gene1-drug ACE      
#3       3 Another ACE study     Gene2-drug ACE      
#4       4 Study of NOS3 and ACE ACE-drug   NOS3, ACE

请注意,您的数据没有"BRCA2". 我"BRCA1"改为"BRCA2".


推荐阅读