Reputation: 330
I have script in which I want to replace a set of strings indicated by ##
script <- c("This is #var1# with a mean of #mean1#")
My key value list is:
pairs <- list(
list("#var1#", "Depression"),
list("#mean1#", "10.1")
)
My loop looks like this and does its job.
for (pair in pairs) {
script <- gsub(pair[[1]], pair[[2]], script)
}
However, does anybody know a way to solve this without using a loop?
Upvotes: 1
Views: 1180
Reputation: 5714
You could use stringr.
As mentioned in ?str_replace
:
To perform multiple replacements in each element of string, pass a named vector (
c(pattern1 = replacement1)
) tostr_replace_all
.
So in your case:
library(stringr)
str_replace_all(script, setNames(sapply(pairs, "[[", 2), sapply(pairs, "[[", 1)))
# [1] "This is Depression with a mean of 10.1"
Upvotes: 2
Reputation: 10781
I think with a few changes, you could use the glue
package. The changes involve using a data.frame
to store your key values, and slightly tweaking the formatting of your text.
library(glue)
tt <- 'This is {var1} with a mean of {mean1}'
dat <- data.frame(
'var1' = c('Depression', 'foo'),
'mean1' = c(10.1, 0),
stringsAsFactors = FALSE
)
glue(tt,
var1 = dat$var1,
mean1 = dat$mean1)
This is Depression with a mean of 10.1
This is foo with a mean of 0
Upvotes: 1