首页 > 解决方案 > R:nel2igraph 和 PN.amalgamation - igraph 未正确生成

问题描述

我遇到了包问题shp2graph。我想使用可以正常PN.amalgamation工作的功能(见下文)。之后,我想创建一个 igraph 对象。这里的代码无法做到这一点。我可以用每个非合并的 shp2graph 对象创建 igraph 对象。

这是我的示例代码,主要是从包的描述中复制粘贴shp2graph

library(igraph)
library(shp2graph)

data(ORN)
rtNEL<-readshpnw(ORN.nt, ELComputed=TRUE)
res.sl<-SL.extraction(rtNEL[[2]],rtNEL[[3]])
res.me<-ME.simplification(res.sl[[1]],res.sl[[2]],DegreeL=res.sl[[4]]) 
res.pn<-PN.amalgamation(res.me[[1]],res.me[[2]],DegreeL=res.me[[4]])
ptcoords<-Nodes.coordinates(res.pn[[1]])
plot(ORN.nt)
points(ptcoords, col="green")
plot(ORN.nt)
points(Nodes.coordinates(rtNEL[[2]]), col="red")

# igraph created from amalgamation is wrong
test <- nel2igraph(nodelist= res.pn[[1]], edgelist=res.pn[[2]], Directed = TRUE)
plot(test,vertex.size=1,edge.width=1,edge.arrow.size=0,vertex.label=NA)

# res.me is one step before amalgamation
test <- nel2igraph(nodelist= res.me[[1]], edgelist=res.me[[2]], Directed = TRUE)
plot(test,vertex.size=1,edge.width=1,edge.arrow.size=0,vertex.label=NA)

任何帮助表示赞赏。

标签: rigraphshapefile

解决方案


我发现该错误以某种方式存在于与igraph包的交互中。问题是创建的节点的标签PN.amalgamation不再是连续的;有些丢失了,因为我们删除了它们。然而,igraph不知何故仍然试图创建它们,然后给出以下警告:

对于在这里遇到同样麻烦的任何人,可以使用一种解决方法,它会重新降低标签。

创建自己的nel2igraph函数:

nel2igraph_corr <- function (nodelist, edgelist, weight = NULL, eadf = NULL, Directed = FALSE) 
{


  nodes <- nodelist[, 1]
  Ne <- length(edgelist[, 1])
  Nn <- length(nodes)

    for (i in 1:Nn) {
      kk <- nodelist[i,][[1]]
      edgelist[which(edgelist[,c(2)]==kk),2] <- i
      edgelist[which(edgelist[,c(3)]==kk),3] <- i

      nodelist[i,][[1]] <- i
  }

    if (!is.null(weight)) {
    if (length(weight) != Ne && is.numeric(weight)) 
      stop("Please give right edge weight, which must be numeric and the same length as edges elment")
  }
  if (!is.null(eadf)) {
    if (length(eadf[, 1]) != Ne) 
      stop("The eadf must be numeric and the same length as edges elment")
  }



  gr <- graph.edgelist(unique(edgelist[, c(2, 3)]), directed = T)
  gr <- set.vertex.attribute(gr, "x", V(gr), Nodes.coordinates(nodelist)[,1])
  gr <- set.vertex.attribute(gr, "y", V(gr), Nodes.coordinates(nodelist)[, 
                                                                         2])
  gr.es <- E(gr)
  if (!is.null(weight)) 
    gr <- set.edge.attribute(gr, "weight", gr.es, weight)
  if (!is.null(eadf)) {
    eanms <- colnames(eadf)
    n <- length(eanms)
    for (i in 1:n) gr <- set.edge.attribute(gr, eanms[i], 
                                            gr.es, eadf[, i])
  }
  gr
}

推荐阅读