R:nel2igraph 和 PN.amalgamation - igraph 未正确生成

R: nel2igraph and PN.amalgamation - igraph not correctly produced

我遇到了包 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)

感谢任何帮助。

我发现这个错误不知何故存在于与 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
}