DN1
DN1

Reputation: 218

How to create a column with values dependent on other columns in r?

I have a dataset of clinical trials for which I am looking to create a column of genes - genes matching the clinical trial they appear in.

My dataset looks like:

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

(Just to note in my real data I have many more columns in which the gene name can appear)

I then have a gene list:

Gene
ACE
BRCA2
NOS3
HER2

I am looking to create a column in my first dataset matching gene to study, outputting for example:

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

I am not sure where to start with this, especially with making a column that also allows the rows to hold multiple genes if multiple genes appear in that row. I've been trying to use dplyr::group_by() but haven't got far.

Input data:

#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"))

Upvotes: 2

Views: 56

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389175

You can create a pattern combining all the genes together. From multiple columns extract the genes which are present and combine them into one column.

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

Note that your data did not have "BRCA2". I changed "BRCA1" to "BRCA2".

Upvotes: 2

Related Questions