How to compare each element of a string to a list

2020-05-09 17:15发布

问题:

Say for example, I have a character vector

a [1] "hi come asap, the show is awsome" "I am suffering from cold"
d [1] "asap" "awsome" "cold" "lol" "rofl"

I should replace any word(from "d") if found in "a" with empty space. How do I implement in R?

回答1:

I think I understand but could be wrong. You could try:

a  <- c("hi come asap, the $#!+ show is awsome", "I am suffering from cold")
d <- c("asap", "awsome", "cold", "lol", "rofl")

library(qdap)
mgsub(d, "", a)

Yields:

> mgsub(d, "", a)
[1] "hi come , the $#!+ show is" "I am suffering from" 


回答2:

Perhaps something like the following would work for you:

a  <- c("hi come asap, the show is awsome", "I am suffering from cold")
d <- c("asap", "awsome", "cold", "lol", "rofl")
d[d %in% gsub("[[:punct:]]", "", unlist(strsplit(a, " ")))] <- " "
d
# [1] " "    " "    " "    "lol"  "rofl"

Or, the opposite way:

a  <- c("hi come asap, the show is awsome", "I am suffering from cold")
d <- c("asap", "awsome", "cold", "lol", "rofl")
gsub(paste(d, collapse = "|"), " ", a)
# [1] "hi come  , the show is  " "I am suffering from  "