【问题标题】:How to create a column with values dependent on other columns in r?如何创建一个值依赖于 r 中其他列的列?
【发布时间】:2020-11-02 13:56:58
【问题描述】:

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

我的数据集如下所示:

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


    【解决方案1】:

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

    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"

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-09
      • 2015-06-17
      • 1970-01-01
      • 1970-01-01
      • 2013-09-18
      • 1970-01-01
      • 2021-07-10
      • 1970-01-01
      相关资源
      最近更新 更多