简体   繁体   English

R在两种不同情况下的邻接矩阵

[英]Adjacency Matrix in R for two different cases

I have a recipe ingredient RxI matrix that looks like this: 我有一个配方成分RxI矩阵,如下所示:

     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. 现在,我想计算RxR邻接矩阵。 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. 如果矩阵中的元素共享任何成分,则它为1。 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: 如果是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

You can use tcrossprod() or mat %*% t(mat) : 您可以使用tcrossprod()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: 对于情况a ,这是情况b的特例,您可以将非零元素替换为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")))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM