我希望使用密钥迭代替换字符串中的文本。我有下面的代码,但我想知道是否有更简单或更有效的方法来做到这一点
library(stringi)
library(magrittr)
library(dplyr)
old_texts = c("blah blah value1 blah blah value2",
"blah value1 blah value2")
key = data_frame(
old = c("value1", "value2"),
new = c("value3", "value4") )
replace_key_individual = function(old_text, key)
key %>%
mutate(call = paste0(
"stri_replace_all_fixed('", old, "','", new, "')") ) %>%
summarize(new_call =
call %>%
paste(collapse = " %>% ")) %>%
`$`(new_call) %>%
paste("old_text %>% ", .) %>%
parse(text = .) %>%
eval
replace_key = function(old_texts, key)
old_texts %>%
sapply(. %>% replace_key_individual(key)) %>%
unname
replace_key(old_texts, key = key)
答案 0 :(得分:2)
如果我理解正确,你可能只想尝试这个:
old_texts %>% stri_replace_all_fixed(key$old, key$new, vectorize_all=FALSE)
#[1] "blah blah value3 blah blah value4"
#[2] "blah value3 blah value4"
# without the pipe operator:
stri_replace_all_fixed(old_texts, key$old, key$new, vectorize_all=FALSE)
答案 1 :(得分:-1)
基函数gsub()使用正则表达式进行文本替换。例如:
old_texts = c("blah blah value1 blah blah value2",
"blah value1 blah value2")
new_text = gsub("value1", "value3", old_texts)
此功能一次只能替换一个值,因此您仍然需要将其包装在某些内容中以实现您的" old"和"新"密钥结构,但使用它将大大简化您的代码。