Home > OS >  How to automate multiple replacement?
How to automate multiple replacement?

Time:10-28

Let's assume I have the following data:

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)

I want to replace "rep" into "df".

I used to run this code but now I get an error (Error in UseMethod("type") : no applicable method for 'type' applied to an object of class "data.frame"):

result = df %>% str_replace_all(rep)

It works if I do:


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

Yet, I want to do it in one shot.

Can anyone help me?

Thanks!

CodePudding user response:

We may need a named vector

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