str_replace_all 具有多个向量模式

问题描述 投票:0回答:1

我想用另一个列表给出的另一种模式替换列表给出的一个模式。

我这样做:

library(stringr)

strings$old <- c("apple banana orange", "peach apple orange", "apple orange pear", "orange apple banana", "apple orange peach")
words to replace <- c("banana", "peach", "pear")
replacements <- c("b", "p", "pe")

我做什么:

current <- paste(c(replace), collapse='|')
change_to <- paste(c(replacements ), collapse='|')
strings$new <- str_replace_all(strings$old, current, change_to)

但是,我得到一个错误。我想看到的是: c("apple b orange", "p apple orange", "apple orange pe", "orange apple b", "apple orange p")

r replace stringr
1个回答
2
投票

您可以在

pattern
函数的
str_replace_all()
参数中使用命名向量,如下所示:

strings %>% 
  mutate(new = str_replace_all(old, setNames(replacements, words_to_replace)))

输出:

                  old             new
1 apple banana orange  apple b orange
2  peach apple orange  p apple orange
3   apple orange pear apple orange pe
4 orange apple banana  orange apple b
5  apple orange peach  apple orange p

输入:

strings = data.frame(old = c("apple banana orange", "peach apple orange", "apple orange pear", "orange apple banana", "apple orange peach"))
words_to_replace <- c("banana", "peach", "pear")
replacements <- c("b", "p", "pe")
© www.soinside.com 2019 - 2024. All rights reserved.