How to split a string column at multiple points in r?

Viewed 95

I have a genetic dataset of gene variant IDs:

VARIANT_ID
01_1254436_A_G_1
02_2254436_A_G_1 
03_3255436_A_G_1 
10_10344745_A_G_1 
11_11256437_A_G_1 
11_11343426_A_G_1 
12_12222431_A_G_1
14_14200436_A_G_1 
15_15256789_A_G_1 

I am looking to make a new column containing a subsection of this data at the first _ and the last _, so looking to output this:

VARIANT_ID           newcol 
01_1254436_A_G_1     1254436_A_G
02_2254436_A_G_1     2254436_A_G
03_3255436_A_G_1     3255436_A_G
10_10344745_A_G_1    10344745_A_G
11_11256437_A_G_1    11256437_A_G
11_11343426_A_G_1    11343426_A_G
12_12222431_A_G_1    12222431_A_G
14_14200436_A_G_1    14200436_A_G
15_15256789_A_G_1    15256789_A_G

I haven't been able to find a similar question in R, so not sure how to approach this, I've tried with str_split_fixed() but this isn't working, any help on what functions to try would be appreciated

Input data:

dput(df)
structure(list(VARIANT_ID = c("01_1254436_A_G_1", "02_2254436_A_G_1", 
"03_3255436_A_G_1", "10_10344745_A_G_1", "11_11256437_A_G_1", 
"11_11343426_A_G_1", "12_12222431_A_G_1", "14_14200436_A_G_1", 
"15_15256789_A_G_1")), row.names = c(NA, -9L), class = c("data.table", 
"data.frame"))
2 Answers

We can utilise a simple RegEx to do the split:

 library(dplyr)
 df %>% 
  mutate(split_string = stringr::str_replace_all(VARIANT_ID,"^\\d{1,}_|_\\d+$",""))

Or:

df %>% 
       mutate(split_string = stringr::str_replace_all(VARIANT_ID,
"^\\d{1,}_(?=\\d{2,})|_\\d$", ""))

Result:

     VARIANT_ID split_string
1:  01_1254436_A_G_1  1254436_A_G
2:  02_2254436_A_G_1  2254436_A_G
3:  03_3255436_A_G_1  3255436_A_G
4: 10_10344745_A_G_1 10344745_A_G
5: 11_11256437_A_G_1 11256437_A_G
6: 11_11343426_A_G_1 11343426_A_G
7: 12_12222431_A_G_1 12222431_A_G
8: 14_14200436_A_G_1 14200436_A_G
9: 15_15256789_A_G_1 15256789_A_G

An option with extract

library(tidyr)
extract(df, VARIANT_ID, into = 'newcol', '^\\d+_(.*)_\\d+$', remove = FALSE)
Related