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

前提是你 提交于 2019-12-24 06:14:04

问题


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.


回答1:


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%]'


来源:https://stackoverflow.com/questions/28529823/replace-string-in-r-giving-a-vector-of-patterns-and-vector-of-replacements

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!