I'm trying to insert a count-suffix after each match in a string.
For example: Inserting a number after each matched "o" in the following string:
"The Apollo program was conceived early in 1960"
Would look like:
"The Apo1llo2 pro3gram was co4nceived early in 1960"
I guess I should use gsub
maybe with perl = TRUE
, but don't know how.
string <- "The Apollo program was conceived early in 1960"
gsub( x = string, pattern = "(o)", replacement = "\\1 $count", perl = TRUE )
Here's one approach:
x <- "The Apollo program was conceived early in 1960"
library(stringi) ## or
pacman::p_load(stringi) ## to load and install if not found
do.call(sprintf, c(list(gsub("o", "o%s", x)), seq_len(stri_count_regex(x, "o"))))
## [1] "The Apo1llo2 pro3gram was co4nceived early in 1960"
Or more succinctly:
pacman::p_load(qdapRegex, stringi)
S(gsub("o", "o%s", x), 1:stri_count_regex(x, "o"))
Note: I maintain the pacman and qdapRegex packages.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With