【问题标题】:R remove words from sentences in dataframeR从数据框中的句子中删除单词
【发布时间】:2021-02-05 20:00:42
【问题描述】:

我有一个数据框,其中包含两列,每列包含句子,我想从另一列中减去一个。我不知何故无法轻易找到执行以下操作的方法:

> c1 <- c("A short story","Not so short")
> c2 <- c("A short", "Not so")
> data.frame(c1, c2)

应该给出 c1 - c2 的结果

"story","short"

任何想法都有帮助。

【问题讨论】:

    标签: r stringr


    【解决方案1】:

    我们可以使用矢量化的str_remove

    library(stringr)
    library(dplyr)
    df1 %>%
       mutate(c3 = str_remove_all(c1, c2))
             c1      c2     c3
    #1 A short story A short  story
    #2  Not so short  Not so  short
    

    【讨论】:

      【解决方案2】:

      你可以这样做:

      c1 <- c("A short story","Not so short")
      c2 <- c("A short", "Not so")
      
      dat <- data.frame(c1, c2)
      dat$c3 <- purrr::map2_chr(c1, c2, ~ trimws(gsub(.y, "", .x)))
      dat
      #>              c1      c2    c3
      #> 1 A short story A short story
      #> 2  Not so short  Not so short
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-04-04
        • 1970-01-01
        • 1970-01-01
        • 2021-08-20
        • 1970-01-01
        • 1970-01-01
        • 2017-02-17
        • 1970-01-01
        相关资源
        最近更新 更多