问题
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