如何自动化多次替换?

How to automate multiple replacement?

假设我有以下数据:

df = data.frame(x = c("ciao he is a good researcher","he is working well on political franchise",
                        "gionny and I have to sort this issue","r leave us in peace"),stringsAsFactors = F)
rep = data.frame(x=c("political_risk","good_researcher"),stringsAsFactors = F)

我想将“rep”替换为“df”。

我以前 运行 这个代码,但现在我得到一个错误 (Error in UseMethod("type") : no applicable method for 'type' applied to an object of class "data.frame"):

result = df %>% str_replace_all(rep)

如果我这样做就有效:


str_replace_all(df$x, c("political risk" = "political_risk", "good researcher" = "good_researcher"))

然而,我想一次完成。

谁能帮帮我?

谢谢!

我们可能需要一个命名向量

library(dplyr)
library(stringr)
df %>% 
   mutate(x = str_replace_all(x,
      setNames(rep$x, c("political risk", "good researcher"))))