How to compare each element of a string to a list

2020-05-09 16:35发布

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?

2条回答
放我归山
2楼-- · 2020-05-09 17:16

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" 
查看更多
家丑人穷心不美
3楼-- · 2020-05-09 17:23

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  "  
查看更多
登录 后发表回答