如何在R igraph中将边缘权重分配给某些边缘

编程入门 行业动态 更新时间:2024-10-25 12:23:39
本文介绍了如何在R igraph中将边缘权重分配给某些边缘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想为最短路径中使用的某些边缘分配较小的非负边缘权重.这是一个示例图:

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中将边缘权重分配给某些边缘

本文发布于:2023-07-18 20:11:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1148593.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:边缘   权重   中将   如何在   igraph

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!