如何在R中计算邻接矩阵

7

我有这些数据。我想在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

2
你目前尝试了什么?我看到你是新来的,也许你还不知道 Stack Overflow 是一个地方,当你尝试但卡住时可以得到编程问题的答案。此时还不清楚你是否尝试解决这个问题。我认为 Stack Overflow FAQ 是一个很好的开始。关于 R 的问题,这篇文章 是必读的。 - SlowLearner
2个回答

10

这里有一个更简单的解决方案,不需要使用 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

9

这至少可以让你开始了解。我能想到的最简单的方法是通过reshape来获取邻接矩阵,然后使用igraph构建图形,具体如下:

# load data
df <- read.table(header=T, stringsAsFactors=F, text="     V1      V2     V3
 164885   431072   3
 164885   164885   24
 431072   431072   5")
> df
#       V1     V2 V3
# 1 164885 431072  3
# 2 164885 164885 24
# 3 431072 431072  5

# using reshape2's dcast to reshape the matrix and set row.names accordingly
require(reshape2)
m <- as.matrix(dcast(df, V1 ~ V2, value.var = "V3", fill=0))[,2:3]
row.names(m) <- colnames(m)

> m
#        164885 431072
# 164885     24      3
# 431072      0      5

# load igraph and construct graph
require(igraph)
g <- graph.adjacency(m, mode="directed", weighted=TRUE, diag=TRUE)
> E(g)$weight # simple check
# [1] 24  3  5

# get adjacency
get.adjacency(g)

# 2 x 2 sparse Matrix of class "dgCMatrix"
#        164885 431072
# 164885      1      1
# 431072      .      1

# get shortest paths from a vertex to all other vertices
shortest.paths(g, mode="out") # check out mode = "all" and "in"
#        164885 431072
# 164885      0      3
# 431072    Inf      0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接