SBala
SBala

Reputation: 85

In R - how do I replace all letters in a string with other letters?

I need to anonymize names but in a very specific way so that the format of the entire string is still the same (spaces, hyphens, periods are preserved) but all the letters are scrambled. I want to consistently replace say all A's with C's, all D's with Z's, and so on. How would I do that?

Upvotes: 2

Views: 184

Answers (2)

William
William

Reputation: 176

Maybe use gsub?

    string <- "ABCDEFG"
    text <- gsub('A', 'C', string )
    string <- gsub('D', 'Z', string )

    string 
    [1] "CBCZEFG"

Upvotes: 2

akrun
akrun

Reputation: 886938

We can use chartr

chartr('AD', 'CZ', str1)
#[1] "CZ,ZC. C"

data

str1 <- c('AD,DA. C')

Upvotes: 6

Related Questions