我有这个数据。我想计算 R 中的邻接矩阵。
我怎样才能做到这一点? V1、V2、V3是列。V1和V2是节点,W3是从V1到V2的权重。这些数据的方向很重要。计算邻接矩阵后,我想用R语言计算这些顶点之间的最短路径。
我怎样才能做到这一点?
V1 V2 V3
[1] 164885 431072 3
[2] 164885 164885 24
[3] 431072 431072 5
最佳答案
这是一个更简单的解决方案,不需要 reshape()
.我们只是直接从您拥有的数据框创建一个 igraph 图。如果你真的需要邻接矩阵,你仍然可以通过get.adjacency()
得到它。 :
library(igraph)
## load data
df <- read.table(header=T, stringsAsFactors=F, text=
" V1 V2 V3
164885 431072 3
164885 164885 24
431072 431072 5")
## create graph
colnames(df) <- c("from", "to", "weight")
g <- graph.data.frame(df)
g
# IGRAPH DNW- 2 3 --
# + attr: name (v/c), weight (e/n)
## get shortest path lengths
shortest.paths(g, mode="out")
# 164885 431072
# 164885 0 3
# 431072 Inf 0
## get the actual shortest path
get.shortest.paths(g, from="164885", to="431072")
# [[1]]
# [1] 1 2
关于r - 如何计算R中的邻接矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14849835/