Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
639 views
in Technique[技术] by (71.8m points)

matrix - How to calculate adjacency matrices in R

I have this data. I want to calculate Adjacency matrices in 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.

How can I do this?

      V1      V2     V3
[1] 164885   431072   3
[2] 164885   164885   24
[3] 431072   431072   5
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is a simpler solution that does not need reshape(). We just create an igraph graph directly from the data frame you have. If you really need the adjacency matrix, you can still get it via 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...