igraph从邻接列表生成邻接矩阵
我在邻接列表中有友谊数据。样本中的每个人(由id表示)最多可以提名5个朋友(f1-f5)。名为“net_test”的数据帧如下所示:igraph从邻接列表生成邻接矩阵,r,igraph,R,Igraph,我在邻接列表中有友谊数据。样本中的每个人(由id表示)最多可以提名5个朋友(f1-f5)。名为“net_test”的数据帧如下所示: id f1 f2 f3 f4 f5 1 1101 1113 1112 NA NA NA 2 1102 1111 1113 1103 1105 NA 3 1103 1105 1110 NA NA NA 4 1104 1115 1106 1110 1109 1112 5 1105 1103 1109 1
id f1 f2 f3 f4 f5
1 1101 1113 1112 NA NA NA
2 1102 1111 1113 1103 1105 NA
3 1103 1105 1110 NA NA NA
4 1104 1115 1106 1110 1109 1112
5 1105 1103 1109 1116 1101 NA
6 1106 1121 1103 1113 NA NA
7 1107 1106 1111 NA NA NA
8 1108 1104 1109 NA NA NA
9 1109 1114 1103 1113 1108 1120
10 1110 1101 1103 1109 1107 NA
第一行是列号。根据这些数据,我想生成一个邻接矩阵,其中ID为行名和列名,如果两个ID有友谊链接,则条目1。我首先尝试将其保存为图形,然后在第二步中生成邻接矩阵:
require(igraph)
netdat<-graph.adjlist(net_test, mode="out", duplicate=FALSE)
adjmat <- get.adjacency(netdat, type="both")
是否有其他方法将邻接列表转换为邻接矩阵?我想问题是,
net\u test
不是合适的邻接列表,因为它包含的不仅仅是两列。所以我要做的第一件事就是通过融化把它变成这种形式:
require(reshape2)
net_list <- melt( net_test, id.vars = "id")
net_list <- net_list[ !is.na(net_list$value), c("id", "value") ]
colnames(net_list) <- c("from", "to")
graph.adjlist(net_list, mode="out", duplicate=FALSE)
# IGRAPH D--- 1121 66 --
你误解了命令。命令
get.adjlist
将igraph图形对象作为参数,并返回图形的列表类型对象表示形式。您正在将其应用于未强制到igraph对象的数据帧
下面是使用数据帧构造igraph图形对象的正确方法,以及如何获取该对象的各种图形表示
require(reshape2)
net_list <- melt( net_test, id.vars = "id")
net_list <- net_list[ !is.na(net_list$value), c("id", "value") ]
graph_o <- graph.data.frame(net_list) #This is a proper igraph graph object
#got from a data frame directly
list_rep <- get.adjlist(graph_o) #this now returns an adjacency list
#representation of your graph
matrix_rep <- get.adjacency(graph_o) #this gives you the adjacency
#matrix as a (sparse) matrix with the row and column names as you want.
require(重塑2)
net_list虽然它以OP想要的形式给出了邻接矩阵,但是OP应该采取一系列igraph惯用的步骤+1表示acast
。虽然这给出了OP要求的内容,但值得注意的是,它从图中排除了孤立节点。net_list[!is.na(net_list$value),c(“id”,“value”)]将删除所有未发送任何链接的用户,并且只有当他们从其他用户处收到链接时,才会显示在图表中。
acast(net_list, from ~ to, fun.aggregate = length )
require(reshape2)
net_list <- melt( net_test, id.vars = "id")
net_list <- net_list[ !is.na(net_list$value), c("id", "value") ]
graph_o <- graph.data.frame(net_list) #This is a proper igraph graph object
#got from a data frame directly
list_rep <- get.adjlist(graph_o) #this now returns an adjacency list
#representation of your graph
matrix_rep <- get.adjacency(graph_o) #this gives you the adjacency
#matrix as a (sparse) matrix with the row and column names as you want.