Building and adjacency matrix

丶灬走出姿态 提交于 2019-12-04 21:49:59

Does the following do what you are looking for?

# simulate data.
d <- data.frame(
  id=c(2,3,4,5,6,6,8,11,11,12,12),
  author=c("FN", "VM","VA","FK","VM","SM","FK","FK","VB","FK","VB")
)

d
   id author
1   2     FN
2   3     VM
3   4     VA
4   5     FK
5   6     VM
6   6     SM
7   8     FK
8  11     FK
9  11     VB
10 12     FK
11 12     VB

# create incidence matrix:
m <- xtabs(~author+id,d)
m
      id
author 2 3 4 5 6 8 11 12
    FK 0 0 0 1 0 1  1  1
    FN 1 0 0 0 0 0  0  0
    SM 0 0 0 0 1 0  0  0
    VA 0 0 1 0 0 0  0  0
    VB 0 0 0 0 0 0  1  1
    VM 0 1 0 0 1 0  0  0

# convert to adjacency matrix.
# tcrossprod does "m %*% t(m)"
tcrossprod(m)
      author
author FK FN SM VA VB VM
    FK  4  0  0  0  2  0
    FN  0  1  0  0  0  0
    SM  0  0  1  0  0  1
    VA  0  0  0  1  0  0
    VB  2  0  0  0  2  0
    VM  0  0  1  0  0  2

Note that crossprod() will give you the incidence matrix for the id variable (i.e. will do t(m) %*% m).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!