如何计算R中的邻接矩阵 [英] How to calculate adjacency matrices in R
本文介绍了如何计算R中的邻接矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个数据.我想在R中计算邻接矩阵.
I have this data. I want to calculate Adjacency matrices in R.
我该怎么做? V1,V2,V3是列.V1和V2是节点,W3是从V1到V2的权重.此数据中的方向很重要.计算邻接矩阵后,我想用R语言计算这些顶点之间的最短路径.
How can I do this? V1,V2,V3 are columns.V1 and V2 are NODES, and W3 are weight from V1 to V2. Direction in this data is important. After calculating the Adjacency matrices, I want to calculate shortest path between these vertices with R language.
我该怎么做?
V1 V2 V3
[1] 164885 431072 3
[2] 164885 164885 24
[3] 431072 431072 5
推荐答案
这至少应该使您入门.我想到的最简单的方法是reshape
,然后使用igraph
构建图,如下所示:
This should at the least get your started. The simplest way I could think of to get the adjacency matrix
is to reshape
this and then build a graph using igraph
as follows:
# 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
这篇关于如何计算R中的邻接矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文