Reputation: 3195
Suppose, I have such a string 1gov2fg3job4qrt
. I want to change the letters according to the following dictionary:
gov=a
fg=b
job=c
qrt=d
So, the output should be:
1a2b3c4d
How can I best do that?
Upvotes: 3
Views: 112
Reputation: 21928
Here is another solution. Since you would like to apply multiple patterns and replacements to the same string, we just pass a named vector to pattern argument:
library(stringr)
str_replace_all(str, (c(gov = "a", fg = "b" , job = "c" , qrt = "d")))
[1] "1a2b3c4d"
Upvotes: 3
Reputation: 4652
As your post is only tagged with r
, I assume you prefer a solution with base R
only.
So, I have built a little function that should do the job! Please find below a reprex.
Reprex
replacechar <- function(patterns, replacements, string) {
.i <- 1
while (.i <= length(patterns)) {
string <- gsub(patterns[.i], replacements[.i], string)
.i <- .i + 1
}
return(string)
}
mystring <- "1gov2fg3job4qrt"
entries <- c("gov", "fg", "job", "qrt")
outputs <- c("a", "b", "c", "d")
replacechar(entries, outputs, mystring)
#> [1] "1a2b3c4d"
Created on 2022-03-17 by the reprex package (v2.0.1)
Upvotes: 3
Reputation: 17250
Try the gsubfn
package, though there are likely base R ways to do it:
#library("gsubfn")
gsubfn::gsubfn('gov|fg|job|qrt', list('gov' = 'a','fg' = 'b', 'job' = 'c', 'qrt' = 'd'), str)
# [1] "1a2b3c4d"
You can also use the stringi
package:
stringi::stri_replace_all_regex(str,
pattern = c("gov", "fg","job","qrt"),
replacement = c("a","b","c","d"),
vectorize = FALSE)
# [1] "1a2b3c4d"
If your dictionary data are in a data frame or similar, you could use:
lib <- data.frame(pattern = c("gov", "fg","job","qrt"), sub = c("a","b","c","d"))
stringi::stri_replace_all_regex(str,
pattern = lib$pattern,
replacement = lib$sub,
vectorize = FALSE)
# [1] "1a2b3c4d"
Upvotes: 2