0

I have a recipe ingredient RxI matrix that looks like this:

     I
R    a  b  c  d  e
1    1  0  1  0  0
2    1  1  1  0  1
3    0  1  1  1  0
4    0  0  0  1  1

Now, I want to compute RxR adjacency matrix. I have few choices on how to calculate elements of the adjacency matrix. Options: a. Element in the matrix is one if it shares any ingredients b. Element in the matrix is number of shared ingredients.

For example,

in case a:

    R
R   1  2  3  4
1   1  1  1  0
2   1  1  1  1
3   1  1  1  1
4   0  1  1  1

In case b:

    R
R   1  2  3  4
1   2  2  1  0
2   2  4  2  1
3   1  2  3  1
4   0  1  1  2
anu
  • 295
  • 2
  • 7
  • 15
  • 1
    See `tcrossprod` -- `tcrossprod(mat)`. To get your "a" result, `tcrossprod(mat) > 0`. See, also, [this post](http://stackoverflow.com/questions/19891278/r-table-of-interactions-case-with-pets-and-houses). – alexis_laz Sep 24 '16 at 19:39

1 Answers1

1

You can use tcrossprod() or mat %*% t(mat):

tcrossprod(mat)
#     [,1] [,2] [,3] [,4]
#[1,]    2    2    1    0
#[2,]    2    4    2    1
#[3,]    1    2    3    1
#[4,]    0    1    1    2

And for case a, it is a special case of case b, you can replace nonzero elements with 1:

tm <- tcrossprod(mat)
tm[tm != 0] = 1
tm
#     [,1] [,2] [,3] [,4]
#[1,]    1    1    1    0
#[2,]    1    1    1    1
#[3,]    1    1    1    1
#[4,]    0    1    1    1

Data:

dput(mat)
structure(c(1L, 1L, 0L, 0L, 0L, 1L, 1L, 0L, 1L, 1L, 1L, 0L, 0L, 
0L, 1L, 1L, 0L, 1L, 0L, 1L), .Dim = 4:5, .Dimnames = list(NULL, 
    c("a", "b", "c", "d", "e")))
Psidom
  • 209,562
  • 33
  • 339
  • 356