Reputation: 489
I am trying to replace each character in a string with following rules using stringr package:
replace_characters <- function(x){str_replace_all(x,c("A"="N",'B'='O','C'='P','D'='Q','E'='R','F'='S','G'='T','H'='U','I'='V','J'='W','K'='X','L'='Y','M'='Z',
'N'='A','O'='B','P'='C','Q'='D','R'='E','S'='F','T'='G','U'='H','V'='I','W'='J','X'='K','Y'='L','Z'='M','0'='5','1'='6','2'='7','3'='8','4'='9','5'='0','6'='1','7'='2','8'='3','9'='4'))}
and then i tried the function with a random string:
replace_characters("HSNKSL584")
and i got:
"HFAKFL034"
as you can see some of the letters(numbers) have been replaced as expected but some remain unchanged. Can anyone explain the reason for me?
Thanks!
Upvotes: 2
Views: 571
Reputation: 887951
We can do this with chartr
from base R
chartr("HSNKL584", "UFAXY039", "HSNKSL584")
#[1] "UFAXFY039"
This can be made into a function
replace_char_fun <- function(str1) {
old <- paste(c(LETTERS, 0:9), collapse="")
new <- paste(c(LETTERS[14:26], LETTERS[1:13], 5:9, 0:4), collapse="")
chartr(old, new, str1)
}
replace_char_fun( "HSNKSL584")
#[1] "UFAXFY039"
Upvotes: 0
Reputation: 29125
Behind the scenes, stringr::str_replace_all
calls upon stringi
's stri_replace_all_*
functions. If you used a named vector to describe multiple replacement patterns (which is the case here), the corresponding parameters fed into stri_replace_all_*
includes vectorize_all = FALSE
.
From stri_replace_all_*
's help file:
However, for stri_replace_all*, if vectorize_all is FALSE, the each substring matching any of the supplied patterns is replaced by a corresponding replacement string. In such a case, the vectorization is over str, and - independently - over pattern and replacement. In other words, this is equivalent to something like for (i in 1:npatterns) str <- stri_replace_all(str, pattern[i], replacement[i]...
As raymkchow & Sotos have noted in the comments, when you cycle through the replacement patterns one by one sequentially, some are going to get affected more than once, effectively reversing the replacement from an earlier cycle.
Upvotes: 4