简体   繁体   中英

replace string in R giving a vector of patterns and vector of replacements

Given a string with different placeholders I want to replace, does R have a function that replace all of them given a vector of patterns and a vector of replacements?

I have managed to accomplish that with a list and a loop

> library(stringr)    
> tt_ori <- 'I have [%VAR1%] and [%VAR2%]'
> tt_out <- tt_ori

> ttlist <- list('\\[%VAR1%\\]'="val-1", '\\[%VAR2%\\]'="val-2")
> ttlist
$`\\[%VAR1%\\]`
[1] "val-1"

$`\\[%VAR2%\\]`
[1] "val-2"

> for(var in names(ttlist)) {
+ print(paste0(var," -> ",ttlist[[var]]))
+ tt_out <- stringr::str_replace_all(string = tt_out, pattern =var, replacement = ttlist[[var]] )
+ }
[1] "\\[%VAR1%\\] -> val-1"
[1] "\\[%VAR2%\\] -> val-2"
> tt_out
[1] "I have val-1 and val-2"

There is a similar question R: gsub, pattern = vector and replacement = vector but it is asking for replacing different strings each one with only one of the patterns. Here I am looking for replacing all the patterns in a single string.

I have tried

> tt_ori <- 'I have VAR1 and VAR2'
> tt_out <- tt_ori
> ttdf <- data.frame(tt=c("VAR1", "VAR2"), val=c("val-1", "val-2"), stringsAsFactors = F)
> str(ttdf)
'data.frame':   2 obs. of  2 variables:
 $ tt : chr  "VAR1" "VAR2"
 $ val: chr  "val-1" "val-2"
> stringr::str_replace_all(string = tt_out, pattern =ttdf$tt, replacement = ttdf$val )
[1] "I have val-1 and VAR2" "I have VAR1 and val-2"

Obviously the output is not what I want (several output strings, every one with only one substitution).

I was wondering if a function exist in base or in a well known CRAN package that would be called like the one shown before and would be capable of doing all substitutions in a single string.

Do someone have a better solution or recomendation for my loop or should I convert it into a function?.

[Note] the strings could be small webpage templates, o configuration files. they are small so making a loop for 10 or 20 substitutions is not a big deal but I am looking for more elegant solutions.

Try

library(qdap)
 mgsub(c('[%VAR1%]' , '[%VAR2%]'), c('val-1', 'val-2'), tt_ori)
#[1] "I have val-1 and val-2"

data

 tt_ori <- 'I have [%VAR1%] and [%VAR2%]'

This seems to achieve what you need.

tt_ori <- 'I have [%VAR1%] and [%VAR2%]'
patterns <- c('\\[%VAR1%\\]', '\\[%VAR2%\\]')
replacements <- c("val-1", "val-2")

stringr::str_replace_all(tt_ori, set_names(replacements, patterns))
# [1] "I have val-1 and val-2"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM