PaulH
PaulH

Reputation: 27

R: Delete element from multiple vectors if only present in a few vectors

How can I delete elements from multiple vectors if they are only present in a few vectors. For example if I have the following 2 vectors

> Text <- c("AB.txt", "B.txt", "C.txt")
> Text2 <- c("B.txt", "C.txt")

Then I try to delete all elements with an 'A' using grep:

> Text[-grep( “A”, Text)]
[1] "B.txt" "C.txt"

However when I do this on Text2 all elements disappear in cyberspace.

> Text2[-grep( “A”, Text2)]
character(0)

How can I change the code so that it works on all vectors?

Thanks in advance,

Paul

Upvotes: 1

Views: 49

Answers (3)

SymbolixAU
SymbolixAU

Reputation: 26258

If you look at what grep("A", Text2) is actually returning:

grep("A", Text2)
# integer(0)

That is, it can't find 'A' in Text2. And therefore your Text2[-integer(0)] won't return anything

You can use grepl to test if the character exists (or doesn't exist in this case, using !)

Text[!grepl("A", Text)]
# [1] "B.txt" "C.txt"
Text2[!grepl("A", Text2)]
# [1] "B.txt" "C.txt"

Here, grepl returns a logical value if the character/pattern is matched. In this example for Text2, 'A' is not found in either element

grepl("A", Text2)
# [1] FALSE FALSE

So now we can 'negate' this, and subset the original vector, which is the same as going Text2[!c(FALSE, FALSE)]

Upvotes: 2

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521249

One option is to determine the indices in Text2 which we do want to retain. This is all indices which do not appear in the grep output.

Text2[!c(1:length(Text2)) %in% grep("A", Text2)]

Upvotes: 0

Roland
Roland

Reputation: 132706

You can use the invert parameter:

Text[grep("A", Text, fixed = TRUE, invert = TRUE)]
#[1] "B.txt" "C.txt"
Text2[grep("A", Text2, fixed = TRUE, invert = TRUE)]
#[1] "B.txt" "C.txt"

Upvotes: 2

Related Questions