Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the complement of vector y in vector x

Tags:

r

vector

That's x \ y using mathematical notation. Suppose

x <- c(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,2,1,1,1,3) 
y <- c(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1)

How can I get a vector with ALL the values in x that are not in y. i.e the result should be:

2,1,1,3

There is a similar question here. However, none of the answers returns the result that I want.

like image 879
George Dontas Avatar asked Mar 21 '10 17:03

George Dontas


People also ask

How do you find the orthogonal complement of a vector?

1: Orthogonal Complement. W⊥={v in Rn∣v⋅w=0 for all w in W}. The symbol W⊥ is sometimes read “W perp.” This is the set of all vectors v in Rn that are orthogonal to all of the vectors in W.

How do you find the complement of a matrix?

Let A ∈ Mm,n{0, 1}. Then the matrix Ac = Jm,n − A is called the complement of A, where Jm,n is the m × n matrix with each entry being 1. It is clear that A and Ac are mutually complementary, i.e., (Ac)c = A.


1 Answers

Here a solution using pmatch (this gives the "complement" as you require):

x <- c(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,2,1,1,1,3)
y <- c(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1)
res <- x[is.na(pmatch(x,y))]

From pmatch documentation:

"If duplicates.ok is FALSE, values of table once matched are excluded from the search for subsequent matches."

like image 198
teucer Avatar answered Oct 29 '22 11:10

teucer