![](/img/trans.png)
[英]How to get the a list of the edge attributes when performing shortest.paths in igraph (R)
[英]R igraph iterate through edge list and get attributes
我正在尝试编写一种有效的方法来打印出两组之间的边缘。 问题是,当我遍历下面的边缘时,我似乎无法弄清楚如何从边缘获取任何信息,谢谢!
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)
我认为您误解了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)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.