给定顶点v1,如何获得边缘(v1,v2)具有最大权重的顶点v2?
我解决问题的方法是:
library(igraph)
maxEdge = max(E(g)[from(id)]$weight
which(E(g)$weight==maxEdge))
但我不知道如何获取顶点ID。有什么想法吗?
最小示例数据
library(igraph)
g1 <- graph.full(5)
V(g1)$name <- 1:5
g2 <- graph.full(5)
V(g2)$name <- 6:10
g3 <- graph.ring(5)
V(g3)$name <- 11:15
g <- g1 + g2 + g3 + edge('1', '6') + edge('1', '11')
V(g)$name <- letters[1:vcount(g)]
# Random data
set.seed(ecount(g))
E(g)$weight <- runif(ecount(g))
maxEdge = max(E(g)[from(1)]$weight)
idEdge = which(E(g)$weight==maxEdge)
我的方法获得边缘ID(idEdge)。但是,想要获取顶点ID!
例如:
V(g)
[1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o"
E(g)[from("a")] -> $weight
[1] b -- a -> 0.97175023
[2] c -- a -> 0.08375751
[3] d -- a -> 0.87386992
[4] e -- a -> 0.32923136
[26] f -- a -> 0.10740653
[27] k -- a -> 0.56277556
考虑到上面的例子,我需要的是一个必须返回“b”或“2”的函数。
答案 0 :(得分:1)
获得具有最大权重的边的ID后,可以使用get.edge(graph, edge.id)
来获取端点的顶点ID。因此,完整的解决方案就像:
edge.seq <- E(g)[from(source)]
max.weight <- max(edge.seq$weight)
get.edges(graph, edge.seq[edge.seq$weight == max.weight])
我不是R的专家,所以也许有一种更简单的方法。
答案 1 :(得分:0)
您可以使用get.adjedgelist
获取所有图表的相邻边缘。然后循环结果列表以获得最大权重的边缘。
lapply(get.adjedgelist(g),
function(x)
E(g)[x[which.max(get.edge.attribute(g,'weight',x))]])
在一个小例子中检查:
library(igraph)
set.seed(123)
g <- graph.full(4)
V(g)$name <- 1:5
V(g)$name <- letters[1:vcount(g)]
E(g)$weight <- runif(ecount(g))
E(g)$label=round(E(g)$weight,2)
ll <- lapply(get.adjedgelist(g),
function(x)
E(g)[x[which.max(get.edge.attribute(g,'weight',x))]])
plot(g,layout=layout.fruchterman.reingold)
$a
Edge sequence:
e
e [2] c -- a
$b
Edge sequence:
e
e [5] d -- b
$c
Edge sequence:
e
e [4] c -- b
$d
Edge sequence:
e
e [5] d -- b