Transform binary vector to binary matrix

  • A+
Category:Languages

I have a binary vector that holds information on whether or not some event happened for some observation:

v <- c(0,1,1,0) 

What I want to achieve is a matrix that holds information on all bivariate pairs of observations in this vector. That is, if two observations both have 0 or both have 1 in this vector v, they should get a 1 in the matrix. If one has 0 and the other has 1, they should get a 0 otherwise.

Hence, the goal is this matrix:

     [,1] [,2] [,3] [,4] [1,]    0    0    0    1 [2,]    0    0    1    0 [3,]    0    1    0    0 [4,]    1    0    0    0 

Whether the main diagonal is 0 or 1 does not matter for me.

Is there an efficient and simple way to achieve this that does not require a combination of if statements and for loops? v might be of considerable size.

Thanks!

 


We can use outer

out <- outer(v, v, `==`) diag(out) <- 0L # as you don't want to compare each element to itself out #     [,1] [,2] [,3] [,4] #[1,]    0    0    0    1 #[2,]    0    0    1    0 #[3,]    0    1    0    0 #[4,]    1    0    0    0 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: