我想为最短路径中使用的某些边分配一个小的非负边权重。这是一个示例图:
library(igraph)
data <- read.table(text="
1 2
1 4
1 5
2 3
2 4
3 4
5 7
5 8
3 6", header=FALSE)
gmatrix <- data.matrix(data, rownames.force = NA) #convert into a matrix to use in igraph
g <- graph_from_edgelist(gmatrix, directed = FALSE)
如果我找到节点 1 和节点 3 之间的最短路径,则使用的边是 1-2 和 1-3。
get.shortest.paths(g, 1,3)
$vpath
$vpath[[1]]
+ 3/9 vertices, from 634c426:
[1] 1 2 3
我想要做的是为这些边缘分配一个小的 epsilon 值。然后,我想调用 get.shortest.paths(g, 1,3)
来测试该函数是否会识别相同的路径。
最佳答案
好的,我可以帮忙:
使用 E()
查询具有从 get.shortest.paths
获取的 id 的边,并将值分配给新的边属性名称(例如,“weight”) “或其他):
p <- get.shortest.paths(g, 1, 3)$vpath[[1]]
E(g, path = p)$weight <- 0.1
检查结果:
> E(g)
+ 9/9 edges from 605e8c7:
[1] 1--2 1--4 1--5 2--3 2--4 3--4 5--7 5--8 3--6
> E(g)$weight
[1] 0.1 NA NA 0.1 NA NA NA NA NA
从 1 到 2 和 2 到 3 的路径现在具有加权边缘。
现在,将零分配给其他边,“get.shortest.paths”标识另一条路径:
> E(g)$weight <- ifelse(is.na(E(g)$weight), 0, E(g)$weight)
> E(g)$weight
[1] 0.1 0.0 0.0 0.1 0.0 0.0 0.0 0.0 0.0
> get.shortest.paths(g, 1, 3, weights = E(g)$weight)
$vpath
$vpath[[1]]
+ 3/8 vertices, from 605e8c7:
[1] 1 4 3
$epath
NULL
$predecessors
NULL
$inbound_edges
NULL
更简洁一点:
g <- set_edge_attr(g, "weight", value = ifelse(E(g) %in% E(g, path = p), 0.1, 0))
E(g)$weight
[1] 0.1 0.0 0.0 0.1 0.0 0.0 0.0 0.0 0.0
关于r - 如何为 R igraph 中的某些边分配边权重,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57577735/