Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

R: remove substring and change the remaining string by addition of a number

in R: I have some strings with the following pattern of letters and numbers

A11B3XyC4
A1B14C23XyC16
B14C23XyC16D3
B14C23C16D3

I want to remove the part "Xy" (always the same letters) and when I do this I want to increase the number behind the Letter B by one (everything else should stay the same).
When there is no "Xy" in the string there is no change to the string
The result should look like this:

A11B4C4
A1B15C23C16
B15C23C16D3
B14C23C16D3

Could you point me to a function capable of this? I struggle with doing a calculation (x+1) with a string.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thank you!

>Solution :

We could use str_replace to do the increment on the substring of numbers that follows the ‘B’ string after removing the ‘Xy’ only for cases where there is ‘Xy’ substring in case_when

library(stringr)
library(dplyr)
case_when(str_detect(str1, "Xy") ~ str_replace(str_remove(str1, 
   "Xy"), "(?<=B)(\\d+)", function(x) as.numeric(x) + 1), TRUE  ~str1)
[1] "A11B4C4"     "A1B15C23C16" "B15C23C16D3" "B14C23C16D3"

data

str1 <- c("A11B3XyC4", "A1B14C23XyC16", "B14C23XyC16D3", "B14C23C16D3")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading