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

How to replace a string with another with interleaving characters in R

I have the following string:

x <- "??????????DRHRTRHLAK??????????"

What I want to do is to replace all the ? characters with
another string

rep <- "ndqeegillkkkkfpssyvv"

Resulting in:

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

ndqeegillkDRHRTRHLAKkkkfpssyvv

Basically, keeping the order of rep in the replacement with the interleaving characters DRHRTRHLAK in x.

The total length of rep is the same as the total length of ?, 20 characters.

Note that I don’t want to split rep manually again as an extra step.

I tried this but failed:

>gsub(pattern = "\\?+", replacement = rep, x = x)
[1] "ndqeegillkkkkfpssyvvDRHRTRHLAKndqeegillkkkkfpssyvv"

>Solution :

You can count the number of ?’s and then cut rep based on that:

x <- "??????????DRHRTRHLAK??????????"
rep <- "ndqeegillkkkkfpssyvv"

pattern <- "(\\?+)(DRHRTRHLAK)(\\?+)"
n <- nchar(gsub(pattern, "\\1", x))

gsub(pattern, paste0(substr(rep, 1, n), "\\2", substr(rep, n+1, nchar(rep))), x)
#[1] "ndqeegillk??????????kkkfpssyvv"
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