1
votes

I am trying to read in an adjacency matrix to create a network in graph I can read the data in with this:

Matrix_One <- read.csv("Network Matrix.csv", header=TRUE)
Matrix <- as.matrix(Matrix_One)
first_network <- graph.adjacency(Matrix, mode= "directed", weighted=NULL)

But this doesn't acknowledge the first column are headers as I'm getting this warning message:

Error in graph.adjacency.dense(adjmatrix, mode = mode, weighted = weighted, : At structure_generators.c:273 : Non-square matrix, Non-square matrix

Any idea how to get R to read column1 as headers?

1
Please show us the first three rows of your csv file and also head(Matrix) and dim(Matrix) - G5W
Oops sorry, it is reading the first row as headers but not the first column. - Zam Zam
"Non-square matrix" refers to your matrix having a height different to its width. Compare nrow(Matrix) width ncol(Matrix) and see how the first column (presumably containing a vertical header) is making your matrix wider than it's tall. - nJGL

1 Answers

0
votes

You'd like to drop the first column of your Matrix like this:

Matrix <- as.matrix(Matrix_One)[,-1]

If the values of your adjacency matrix are numeric, it might be recommendable to use data.matrix() instead of as.matrix() to get numeric values instead of strings in your matrix. Often the values in the adjacency matrix are weights corresponding to each edge-weight given as a numeric value.

To get R to read your data as a usable adjacency matrix, consider this:

 # Assuming your csv file is like this...
csv <- "X,A,B,C,B,E
        A,0,0,1,0,1
        B,1,0,0,0,0
        C,1,1,0,0,0
        D,1,0,0,0,0
        E,0,0,0,0,0"
# ... with first row and column indicating node name in your network.

# To keep names, we could keep the header and use it as a list of nodes:
Matrix_One <- read.csv2("Network Matrix.csv", sep=",", header=TRUE)
Nodelist <- names(Matrix_One)[-1]

# The matrix should include the first row (which is data),
# but not the first column (which too contains node-names) of the df:
Matrix <- data.matrix(Matrix_One)[,-1]
# As the matrix is now of the size N by N, row- and colnames makes for a neat matrix:
rownames(Matrix) <- colnames(Matrix) <- Nodelist

# Look at it
Matrix

# Use igraph to make a graph-object and visualize it
library(igraph)
g <- graph_from_adjacency_matrix(Matrix, mode="directed", weighted=NULL)
plot(g)

The package graph is outdated (and removed from CRAN I believe). The above example uses igrpah instead, which is a comprehensive network data management package with some nice visualization. The result from the code above will be something like this:

enter image description here

If you choose to stick to graph, your like first_network <- graph.adjacency(Matrix, mode= "directed", weighted=NULL) takes the square Matrix too.