【问题标题】:igraph generate adjacency matrix from adjacency listigraph 从邻接表生成邻接矩阵
【发布时间】:2014-10-19 11:20:51
【问题描述】:

我在邻接列表中有友谊数据。样本中的每个人(用 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 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")

当我应用 graph.adjlist 命令时,出现以下错误:

At structure_generators.c:84 : Invalid (negative) vertex id, Invalid vertex id

是否有另一种方法可以将邻接表转换为邻接矩阵?

【问题讨论】:

    标签: r igraph


    【解决方案1】:

    您误解了命令。命令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.
    

    【讨论】:

    • 虽然这给出了 OP 的要求,但很高兴注意到它从图中排除了孤立的节点。 net_list[ !is.na(net_list$value), c("id", "value") ] 删除所有不发送任何链接的人,并且只有在收到其他人的链接时才会出现在图表中.
    【解决方案2】:

    我想问题是,net_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 --
    

    如果你只需要邻接矩阵而不再需要igraph,你可以直接cast熔化的net_list

    acast(net_list, from ~ to, fun.aggregate = length )
    

    【讨论】:

    • 虽然这以 OP 想要的形式给出了邻接矩阵,但 OP 应该采取一系列 igraph 惯用的步骤。 +1 acast
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-31
    • 2016-04-06
    相关资源
    最近更新 更多