我想为最短路径中使用的某些边缘分配较小的非负边缘权重.这是一个示例图:
I'd like to assign a small, non-negative edge weights to certain edges used in a shortest path. Here is an example graph:
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.
If I find the shortest path between node 1 and node 3, the edges used are 1-2 and 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)来测试该函数是否会标识相同的路径.
What I want to do is to assign a small epsilon value to those edges. Then, I'd like to call get.shortest.paths(g, 1,3) to test whether the function will identify the same path or not.
推荐答案好的,我可以帮助您:
使用 E()查询具有从 get.shortest.paths 中获取的ID的边缘,并将值分配给新的边缘属性名称(例如,"weight"")
Use E() to query the edges with the ids grabbed from get.shortest.paths and assign the values to a new edge attribute name (e.g., "weight" or whatever):
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的路径现在具有加权边.
The path from 1 to 2 and 2 to 3 now has a weighted edge.
现在,将零分配给其他边,并且'get.shortest.paths`标识另一条路径:
Now, assign zero to the other edges and 'get.shortest.paths` identifies another path:
> 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 igraph中将边缘权重分配给某些边缘
发布评论