Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create a binary matrix from single vector in R?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

   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!

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading