R remove words from sentences in dataframe

我与影子孤独终老i 提交于 2021-02-16 14:06:09

问题


I have one dataframe with two columns which each containing sentences and I would like to subtract one from the other. I somehow can't easily find a method to do the following:

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

which should give the result of c1 - c2

"story","short"

Any ideas are helpful.


回答1:


We can use str_remove which is vectorized

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:


You could do:

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


来源:https://stackoverflow.com/questions/66069842/r-remove-words-from-sentences-in-dataframe

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!