wolf_wue wolf_wue -4 years ago 186
R Question

R: Remove vector elements from vector elements

I think the title is a bit confusing, but here my problem:
I have 2 vectors, one containing some text the other one containing some phrases

text <- c("this is some text","some elements should be removed", "i hope you can help me with this text element problem")
pattern <- c("text", "some","be")

And now I want to remove all elements from
which are in text, so as result vector

[1] "this is"
[2] "elements should removed"
[3] "i hope you can help me with this element problem"

I tried

text_result <- sapply(pattern, function(x) gsub(x, text, replacement =""))


text_result <- sapply(text, function(y) sapply(pattern, function(x)gsub(x,y,replacement ="")))

but in both cases I receive a large matrix with

length(pattern)*length(text) elements

thanks in advance!

Answer Source

You can try:

`%notin%` <- function(x,y) !(x %in% y)
 lapply(strsplit(text," "),function(x) paste(x[x %notin% pattern],collapse=" "))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download