【问题标题】:How to automate multiple replacement?如何自动进行多次更换?
【发布时间】:2021-12-12 21:27:31
【问题描述】:

假设我有以下数据:

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"))

但是,我想一口气完成。

谁能帮帮我?

谢谢!

【问题讨论】:

    标签: r dataframe str-replace


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-27
      • 1970-01-01
      • 2011-02-07
      • 2020-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多