'How to change a string according to an existing dictionary?
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?
Solution 1:[1]
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
- Code of the function
replacechar <- function(patterns, replacements, string) {
.i <- 1
while (.i <= length(patterns)) {
string <- gsub(patterns[.i], replacements[.i], string)
.i <- .i + 1
}
return(string)
}
- Using the function
mystring <- "1gov2fg3job4qrt"
entries <- c("gov", "fg", "job", "qrt")
outputs <- c("a", "b", "c", "d")
replacechar(entries, outputs, mystring)
- Output
#> [1] "1a2b3c4d"
Created on 2022-03-17 by the reprex package (v2.0.1)
Solution 2:[2]
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"
Solution 3:[3]
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"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | lovalery |
| Solution 2 | Anoushiravan R |
| Solution 3 |
