R 从数据帧创建SNA的邻接矩阵
我想创建一个邻接矩阵,用于社交网络分析(可能是IGRAPHE中邻接矩阵中的图形),其结构如下(但要大得多): 对于网络分析,节点将是名称变量,节点将通过一起投票的频率(1或0)进行连接。比如:R 从数据帧创建SNA的邻接矩阵,r,matrix,adjacency-matrix,network-analysis,R,Matrix,Adjacency Matrix,Network Analysis,我想创建一个邻接矩阵,用于社交网络分析(可能是IGRAPHE中邻接矩阵中的图形),其结构如下(但要大得多): 对于网络分析,节点将是名称变量,节点将通过一起投票的频率(1或0)进行连接。比如: Joe Jane Jill Joe 0 2 3 Jane 2 0 2 Jill 3 2 0 虽然看起来很简单,但我还未能成功地将此数据帧转换为可用于创建igraph图形对象的邻接矩阵。as.matrix和data.matrix会将其转换为矩阵,但不会转换为邻
Joe Jane Jill
Joe 0 2 3
Jane 2 0 2
Jill 3 2 0
虽然看起来很简单,但我还未能成功地将此数据帧转换为可用于创建igraph图形对象的邻接矩阵。as.matrix和data.matrix会将其转换为矩阵,但不会转换为邻接矩阵,也不会转换为保留“name”变量中字符的矩阵。我的矩阵代数不是很强,所以我知道我可能遗漏了一些明显的东西,但我不知道它是什么。我对其他解决方案持开放态度,这些解决方案可以帮助我实现网络分析的最终目标。我想你需要一些版本的交叉产品
# 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
使用这个较大的矩阵运行上述过程,我们得到
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,鲍勃·吉尔·吉尔·鲍勃的位置都是3,因为他们都投了同样的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))
df我想你需要交叉积的一些版本
# 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
使用这个较大的矩阵运行上述过程,我们得到
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,鲍勃·吉尔·吉尔·鲍勃的位置都是3,因为他们都投了同样的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))
df这正是我需要的。我最终使用了data.matrix'而不是as.matrix',但这是唯一的修改。我忘了那个函数了。好发现。这正是我需要的。我最终使用了data.matrix'而不是as.matrix',但这是唯一的修改。我忘了那个函数了。好发现。