R从数据框中的句子中删除单词

R remove words from sentences in dataframe

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

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

应该给出 c1 - c2 的结果

"story","short"

任何想法都有帮助。

你可以这样做:

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

我们可以使用矢量化的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