R 如何将带有虚拟变量的数据帧转换为邻接矩阵?

R 如何将带有虚拟变量的数据帧转换为邻接矩阵?,r,nlp,sna,R,Nlp,Sna,我有一个带有多个虚拟变量的数据帧 df我想我缺少了一些简单的方法来实现这一点,但是基本Router的一个选项是 cols <- names(df) apply_fun <- function(x, y) sum(df[x] == 1 & df[y] == 1) mat <- outer(cols,cols, Vectorize(apply_fun)) row.names(mat) <- cols colnames(mat) <- cols mat # A

我有一个带有多个虚拟变量的数据帧


df我想我缺少了一些简单的方法来实现这一点,但是基本R
outer
的一个选项是

cols <- names(df)
apply_fun <- function(x, y) sum(df[x] == 1 & df[y] == 1)
mat <- outer(cols,cols, Vectorize(apply_fun))
row.names(mat) <- cols
colnames(mat) <- cols

mat
#  A B C
#A 3 2 1
#B 2 3 1
#C 1 1 3
cols