Home > front end >  How to create a binary matrix from single vector in R?
How to create a binary matrix from single vector in R?

Time:12-28

I have a vector of the form:

myVec <- c("A", "A", "A", "B", "B", "C", "A")

What I would like to create is a relational matrix with myVec as the columns and rows of the matrix where there are 1's when the column and row values are equal.

From the example vector above the resulting matrix would be:

   A  A  A  B  B  C  C  A
A  1  1  1  0  0  0  0  1
A  1  1  1  0  0  0  0  1
A  1  1  1  0  0  0  0  1
B  0  0  0  1  1  0  0  0
B  0  0  0  1  1  0  0  0
C  0  0  0  0  0  1  1  0
C  0  0  0  0  0  1  1  0
A  1  1  1  0  0  0  0  1

It's fine if the row and column names come out as (A1, A2, A3, B1, ...) or other 'unique' configuration.

I'm sure there has to be an easy solution to this problem, but it's eluding me. How can I accomplish this? Thanks!

CodePudding user response:

Try this

>  outer(myVec, myVec, `==`)
     [,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,]    1    1    1    0    0    0    1
[2,]    1    1    1    0    0    0    1
[3,]    1    1    1    0    0    0    1
[4,]    0    0    0    1    1    0    0
[5,]    0    0    0    1    1    0    0
[6,]    0    0    0    0    0    1    0
[7,]    1    1    1    0    0    0    1
  • Related