在R中使用iGraph获得路径的权重 [英] Obtain weight of a path with iGraph in R

查看:381
本文介绍了在R中使用iGraph获得路径的权重的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从数据框创建的图形,其格式为from, to, cost列.我也有一条有效的路径(作为一系列顶点,以igraphvpath格式)(我的图形是有向的).

I have a graph I created from a data frame, in the form of from, to, cost columns. I also have a path (as a succession of vertexes, in the vpath format of igraph) which is valid (my graph is directed).

给定我的图形和路径,是否有任何函数会给我该路径的成本?

Is there any function that, given my graph and my path, would give me the cost of that path?

我并没有要求最短的路径,因为我是从all_shortest_paths获得路径的.但是,我只获得节点继承,而没有获得路径的权重,这也是我所需要的.

I'm not asking for the shortest path, as I obtained the path from all_shortest_paths. However, I only get the node succession and not the weight of the path, which I also need.

修改:数据

这是我的数据框,我将其变成图表: http://www. sharecsv.com/s/47209742f0052a37e17db37ea3af63ac/arcsWithCost.csv

This is my dataframe which I turn into the graph: http://www.sharecsv.com/s/47209742f0052a37e17db37ea3af63ac/arcsWithCost.csv

我的路径是15 4 50 212 183 112 114 37 228 119

推荐答案

您将路径作为一系列顶点.如果您有边缘的顺序,这将很容易-只需将每个边缘的权重相加即可.因此,您需要做的是将顶点序列转换为边线序列.这就是get.edge.ids的作用,尽管您需要将数据转换为正确的格式.

You have the path as a sequence of vertices. If you had the sequence of edges, this would be easy - just add up the weights for each edge. So what you need to do is convert the sequence of vertices to a sequence of edges. That is what get.edge.ids does, although you need to get the data into the right format.

由于您未提供任何数据,因此我将通过一个随机示例进行说明.

Since you do not provide any data, I will illustrate with a random example.

library(igraph)
set.seed(1234)
g = erdos.renyi.game(10,0.15, directed=TRUE)
E(g)$weight = sample(5, length(E(g)), replace=TRUE)
plot(g)

好的,现在假设我们要对来自节点1-4-10-3的路径上的权重求和. 我假设您有一个列表c(1,4,10,3)

OK, now suppose we want to sum the weights along the path from nodes 1-4-10-3. I assume that you have a list c(1,4,10,3)

VP = c(1,4,10,3)
EP = rep(VP, each=2)[-1]
EP = EP[-length(EP)]
E(g)$weight[get.edge.ids(g, EP)]
[1] 1 5 4
sum(E(g)$weight[get.edge.ids(g, EP)])
[1] 10

添加:

在添加到问题的数据中,有110个节点,但它们的编号最多为281.这些数字是节点的标签,而不是节点ID.您可以使用标签来访问节点,但是必须将它们转换为字符串,才能将它们视为标签.此代码适用于您的示例.

Addition:

In the data added to the question, there are 110 nodes but they are numbered up to 281. These numbers are labels for the nodes, but not the node IDs. You can use the labels to access the nodes, but you must convert them to strings for them to be treated as the labels. This code worked on your example.

VP = c(15, 4, 50, 212, 183, 112, 114, 37, 228, 119)
EP = rep(VP, each=2)[-1]
EP = EP[-length(EP)]
E(g)$cost[get.edge.ids(g, as.character(EP))]
sum(E(g)$cost[get.edge.ids(g, as.character(EP))])

这篇关于在R中使用iGraph获得路径的权重的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆