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:
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"