How to calculate adjacency matrices in R

I have this data. I want to compute Adjacency matrices in R.

How can i do this? V1, V2, V3 are columns. V1 and V2 are NODES, and W3 is a weight from V1 to V2. The direction in this data is important. After calculating the Adjacency matrices, I want to calculate the 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 
+6
source share
2 answers

That should at least start. The easiest way to get the adjacency matrix is to reshape and then build the 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 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 
+9
source

Here is a simpler solution that does not need reshape() . We simply create a graph of graphs directly from the data frame you are using. If you really need an 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 
+9
source

All Articles