【问题标题】:How to replace part of a string in one row with a word from another row?如何用另一行中的单词替换一行中的部分字符串?
【发布时间】:2019-11-28 15:50:12
【问题描述】:

我正在尝试用 R 中数据框同一行的另一列中的单词从一行中填充模板。

这是我想要做的一个例子:

x <- data.frame("replacement" = c("two", "ten"), 
"text" = c("we had <replacement> books", "we had <replacement> books"),
"result" = c("we had two books", "we had ten books"))

我尝试使用 gsub,但它会替换所有单词而不是一个:

x$result <- gsub("\\<.+?\\>", x$replacement, x$text)

【问题讨论】:

    标签: r regex dataframe


    【解决方案1】:

    dplyr,你也可以试试:

    x %>%
     rowwise() %>%
     mutate(result = sub("<replacement>", replacement, text, fixed = TRUE))
    

    【讨论】:

      【解决方案2】:

      我们可以像文档 (?str_replace) 所说的那样使用str_replace

      对字符串、模式和替换进行矢量化。

      library(stringr)
      library(dplyr)
      library(magrittr)
      x %<>%
        mutate(result = str_replace(text, "<replacement>", as.character(replacement)))
      

      【讨论】:

      • 谢谢,这行得通 :) 如何将其保存在“结果”列中?
      • @alinaz 只需将mutate中的“文本”更改为“结果”即可
      • @alinaz 为了让它更快,你可以用fixed("&lt;replacement&gt;")包装
      猜你喜欢
      • 2014-01-04
      • 1970-01-01
      • 1970-01-01
      • 2023-04-03
      • 2020-09-01
      • 2019-09-26
      • 1970-01-01
      • 1970-01-01
      • 2022-12-28
      相关资源
      最近更新 更多