R-从数据框架创建SNA的邻接矩阵



我想创建一个与社交网络分析中使用的邻接矩阵(可能与graph_from_adjacency_matrix in igraph中的graph_from_adjacency_matrix一起使用),该csv构成这样(但更大):

>
name vote1 vote2 vote3
Joe  1     0     1
Jane 0     0     1
Jill 1     0     1

对于网络分析,节点将是名称变量,并且节点将通过他们一起投票的频率(1或0)连接。类似:

    Joe Jane Jill
Joe  0    2    3
Jane 2    0    2
Jill 3    2    0

看起来很简单,我无法成功将此数据框架转换为可用于创建Igraph图对象的邻接矩阵。as.matrix和data.matrix确实将其转换为矩阵,而不是邻接矩阵,而不是保留"名称"变量中字符的矩阵。我的矩阵代数并不强,所以我知道我可能会错过一些明显的东西,但是我不知道它是什么。我对其他解决方案开放,这些解决方案使我达到了网络分析的最终目标。

我认为您想要跨产品的某个版本。

# construct the matrix
myMat <- as.matrix(df[-1])
# same output as myMat %*% t(myMat)
resultMat <- tcrossprod(myMat)
# add names
dimnames(resultMat) <-  list(df$name, df$name)
resultMat
     Joe Jane Jill
Joe    2    1    2
Jane   1    1    1
Jill   2    1    2

对角线表明了个人同时投票和对角线的实例计数,该计数给出了个人对自己投票的次数(即他们的总投票数)。

由于您不希望每个人的总投票计数,因此可以用0替换对角线。

# remove diagonal
diag(resultMat) <- 0
resultMat
     Joe Jane Jill
Joe    0    1    2
Jane   1    0    1
Jill   2    1    0

在下面的DF1中增加了两票和另外两个选民。有一个名为SAL的选民,他只投票2投票,并且是唯一的选民。

df1
 name vote1 vote2 vote3 vote4 vote5
1  Joe     1     0     1     0     1
2 Jane     0     0     1     1     0
3 Jill     1     0     1     1     0
4  Bob     1     0     1     1     0
5  Sal     0     1     0     0     0

使用此较大矩阵贯穿上述过程,我们得到

resultMat
     Joe Jane Jill Bob Sal
Joe    0    1    2   2   0
Jane   1    0    2   2   0
Jill   2    2    0   3   0
Bob    2    2    3   0   0
Sal    0    0    0   0   0

在萨尔的所有插槽中显示0,鲍勃·吉尔·吉尔·鲍勃(Bob-Jill Jill-Bob)的插槽中显示了0s,因为他们俩都以相同的3票进行了投票。

数据

df <-
structure(list(name = structure(c(3L, 1L, 2L), .Label = c("Jane", 
"Jill", "Joe"), class = "factor"), vote1 = c(1L, 0L, 1L), vote2 = c(0L, 
0L, 0L), vote3 = c(1L, 1L, 1L)), .Names = c("name", "vote1", 
"vote2", "vote3"), class = "data.frame", row.names = c(NA, -3L))
df1 <- 
structure(list(name = structure(c(4L, 2L, 3L, 1L, 5L), .Label = c("Bob", 
"Jane", "Jill", "Joe", "Sal"), class = "factor"), vote1 = c(1L, 
0L, 1L, 1L, 0L), vote2 = c(0L, 0L, 0L, 0L, 1L), vote3 = c(1L, 
1L, 1L, 1L, 0L), vote4 = c(0L, 1L, 1L, 1L, 0L), vote5 = c(1L, 
0L, 0L, 0L, 0L)), .Names = c("name", "vote1", "vote2", "vote3", 
"vote4", "vote5"), class = "data.frame", row.names = c(NA, -5L))

最新更新