如果通过 dplyr 和 stringr 进行字符串,有没有办法将一组字符串替换为另一组字符串

Don*_*wis 3 r stringr dplyr tidyverse

我重现了我的问题的简单版本。我本质上想将所有语句的语句列中的英语单词替换为西班牙语等效单词。

library(tidyverse)
english <- c('hello','world','my','name', 'is')
spanish <- c('hola','mundo','mi','nombre', 'es')
statement <-c('Hello my name is john doe',' hello world','my name is world','hello john, my world is','jane is my world ')

df <- data.frame(english,spanish,statement)  
df
Run Code Online (Sandbox Code Playgroud)

我试过

df %>% 
  str_replace_all(statement, c(df$english), c(df$spanish))
Run Code Online (Sandbox Code Playgroud)

str_replace_all(statement, c(df$english), c(df$spanish)).
Run Code Online (Sandbox Code Playgroud)

第二次尝试让我更接近我的答案。仅替换了一个答案。

And*_*ter 5

作为一个超级简单的解决方案,str_replace_all采用命名向量并自动匹配所有内容:

library(tidyverse)
english <- c('hello','world','my','name', 'is')
spanish <- c('hola','mundo','mi','nombre', 'es')
statement <-c('Hello my name is john doe',' hello world','my name is world','hello john, my world is','jane is my world ')

names(spanish) <- english

str_replace_all(statement, spanish)
#> [1] "Hello mi nombre es john doe" " hola mundo"                
#> [3] "mi nombre es mundo"          "hola john, mi mundo es"     
#> [5] "jane es mi mundo "
Run Code Online (Sandbox Code Playgroud)