如何计算R中的邻接矩阵

时间:2013-02-13 09:03:13

标签: r matrix

我有这些数据。我想在R中计算邻接矩阵。

我该怎么做? V1,V2,V3为列.V1和V2为NODES,W3为V1至V2的权重。此数据的方向很重要。在计算邻接矩阵之后,我想用R语言计算这些顶点之间的最短路径。

我该怎么做?

      V1      V2     V3
[1] 164885   431072   3
[2] 164885   164885   24
[3] 431072   431072   5

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:9)

这应该至少让你开始。我能想到获得adjacency matrix的最简单方法是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
相关问题