Marcin
Marcin

Reputation: 8044

How not to lose copied elements in setdiff in R?

I am using setdiff function to extract elements of first set that are not in the other set. But after evaluating setdiff I receive such elements but they are single values (not such many as there were in first set); like this:

> setdiff( c("x", "x", "y"), c("y"))
[1] "x"

Is there a smarter way to extract such elements but in an amount that there were in a first set such as a result of this line?

> c("x","x","y")[ c("x","x","y") %in% setdiff( c("x", "x", "y"), c("y"))]
[1] "x" "x"

Upvotes: 1

Views: 66

Answers (1)

Matthew Lundberg
Matthew Lundberg

Reputation: 42659

Invert the match for %in% to make the expression simpler, and leave setdiff behind:

> x <- c("x","x","y")
> x
[1] "x" "x" "y"
> x[!x %in% c("y")]
[1] "x" "x"

Upvotes: 3

Related Questions