替换 R 中的字符串,给出模式向量和替换向量 [英] replace string in R giving a vector of patterns and vector of replacements

查看:33
本文介绍了替换 R 中的字符串,给出模式向量和替换向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个我想替换的具有不同占位符的字符串,R 是否有一个函数可以替换所有给定的模式向量和替换向量?

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"

有一个类似的问题 R: gsub, pattern = vector and replacement =vector 但它要求只用一种模式替换不同的字符串.在这里,我正在寻找替换单个字符串中的所有模式.

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.

我试过了

> 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).

我想知道 base 或众所周知的 CRAN 包中是否存在一个函数,该函数将像前面显示的那样调用,并且能够在单个字符串中进行所有替换.

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?.

[注意] 字符串可以是小网页模板,o 配置文件.它们很小,所以循环 10 或 20 次替换并不是什么大问题,但我正在寻找更优雅的解决方案.

[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.

推荐答案

尝试

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

数据

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

这篇关于替换 R 中的字符串,给出模式向量和替换向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆