Replacing multiple punctuation marks in a column of data

Viewed 47

Column in a df:

chr10:123453:A:C
chr10:2345543:TTTG:CG
chr10:3454757:G:C
chr10:4567875765:C:G

Desired output:

chr10:123453_A/C
chr10:2345543_TTTG/CG
chr10:3454757_G/C
chr10:4567875765_C/G

I think I could use stingsplit but I wanted to try and do it all in a R oneliner. Any ideas would be greatly welcome!

1 Answers

Try this:

gsub(":([A-Z]+):([A-Z]+)$", "_\\1/\\2", x, perl = TRUE)
[1] "chr10:123453_A/C"      "chr10:2345543_TTTG/CG" 

Here we use backreference twice: \\1 recollects what's between the pre-ultimate and the ultimate :, whereas \\2 recollects what's after the ultimate :.

Data:

x <- c("chr10:123453:A:C","chr10:2345543:TTTG:CG")
Related