R igraph迭代边缘列表并获得属性

时间:2014-07-21 01:33:08

标签: r igraph

我试图写一种有效的方法来打印两组之间的边缘。问题是当我在下面的边缘迭代时,我似乎无法弄清楚如何从边缘获取任何信息,谢谢!

myG <- erdos.renyi.game(100, 10/100)

E(myG)$weight <- runif(ecount(myG))

V(myG)$group <- ifelse(runif(100)>0.5,1,2)
V(myG)$origIndex <- seq(1,vcount(myG))
V(myG)$label <- paste(sample(LETTERS,vcount(myG), replace=TRUE),     sample(LETTERS,vcount(myG), replace=TRUE),sample(LETTERS,vcount(myG), replace=TRUE),sep="-")

indices1 <- which(V(myG)$group == 1)
indices2 <- which(V(myG)$group == 2)
edgeIDsOfAllBetween <- myG[[indices1, indices2, edges=TRUE]]

uniqueEdgeIDs <- unique(unlist(edgeIDsOfAllBetween))
edgeList <- E(myG)[uniqueEdgeIDs] 
rows <- length(edgeList)

if(rows>0){
  for(r in 1:rows){

    edgeIndex <- edgeList[r]  #how to get the original index??
    weight <- get.edge.attribute(myG, "weight", index= edgeIndex)
    n1Index <- edgeList[r,1] #how to get the index of the first vertex????
    n2Index <- edgeList[r,2] #how to get the index of the second vertex????
    n1IndexisIN1 <- n1Index %in% indices1

    n1 <- get.vertex.attribute(myG,"label",index = n1Index)
    n2 <- get.vertex.attribute(myG,"label",index = n2Index)

    if(n1IndexisIN1){
      n1 <- paste("group1_",n1,sep="")
      n2 <- paste("group2_",n2,sep="")
    }else{
      n1 <- paste("group2_",n1,sep="")
      n2 <- paste("group1_",n2,sep="")
    }

    print(paste(n1, " ", n2, "  weight: ", weight, sep=""))
  }
}

更新: 有没有比转换为data.frame更快的方法?:

MyEdges <- as.data.frame(get.edgelist(myG))
MyEdges$origindex <- seq(1, ecount(myG))
MyEdges <- subset(MyEdges, origindex %in% uniqueEdgeIDs )

rows <- nrow(MyEdges)

1 个答案:

答案 0 :(得分:5)

我认为你误解了edgeList是什么以及如何访问它。

你试着迭代它:

for(r in 1:rows){
    edgeIndex <- edgeList[r]

但它提取边缘本身,而不是索引:

> edgeList[1]
Edge sequence:
    e       
e [1] 3 -- 1

但这甚至不是边缘列表中的第一个边缘!它实际上是图中的边数1!

我怀疑你只想迭代边缘列表本身:

> for(edge in edgeList){
+ print(edge)
+ }
[1] 57
[1] 272
[1] 1
[1] 7

这些可能是您正在寻找的边缘指数。

> E(myG)[57]
Edge sequence:
     e         
e [57] 34 --  2
> V(myG)[34]$group
[1] 2
> V(myG)[2]$group
[1] 1

在这些边上进行简单的循环,得到边的顶点并打印出两个组,然后每次打印出1和2(或2和1):

> for(edge in edgeList){
 verts = get.edge(myG,edge)
 print(V(myG)[verts[1]]$group) ; print(V(myG)[verts[2]]$group)
 }