r - 如何为 R igraph 中的某些边分配边权重

标签 r igraph

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

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/

相关文章:

r - 使用 ggplot2 绘制圆形密度图

Python-IGraph/网络x : Find clusters of specific nodes in connected graph

r - 以最小距离连接矩阵的两个坐标

r - 如何使用igraph将两个节点合并为单个节点

r - 循环遍历 2 个数据框以识别公共(public)列

r - 根据 R 中其他列的变化增加列记录

json - 转置 JSON 字典列表以在 R 中进行分析

R格子: Change panel title layout

r - 如何在 igraph(R) 中发现社区检测后的度量?

r - 使用 igraph 根据边缘属性添加多个边缘