rliststr-replaceremap

R How to remap letters in a string


I’d be grateful for suggestions as to how to remap letters in strings in a map-specified way.

Suppose, for instance, I want to change all As to Bs, all Bs to Ds, and all Ds to Fs. If I do it like this, it doesn’t do what I want since it applies the transformations successively:

"abc" %>% str_replace_all(c(a = "b", b = "d", d = "f"))

Here’s a way I can do what I want, but it feels a bit clunky.

f <- function (str) str_c( c(a = "b", b = "d", c = "c", d = "f") %>% .[ strsplit(str, "")[[1]] ], collapse = "" )

"abc" %>% map_chr(f)

Better ideas would be much appreciated.

James.

P.S. Forgot to specify. Sometimes I want to replace a letter with multiple letters, e.g., replace all As with the string ZZZ.

P.P.S. Ideally, this would be able to handle vectors of strings too, e.g., c("abc", "gersgaesg", etc.)


Solution

  • We could use chartr in base R

    chartr("abc", "bdf", "abbbce")
    #[1] "bdddfe"
    

    Or a package solution would be mgsub which would also match and replace strings with number of characters greater than 1

    library(mgsub)
    mgsub("abbbce",  c("a", "b", "c"), c("b", "d", "f"))
    #[1] "bdddfe"
    
    mgsub("abbbce",  c("a", "b", "c"), c("ba", "ZZZ", "f"))
    #[1] "baZZZZZZZZZfe"