简体   繁体   中英

Read first column as header in matrix for unsquare matrix

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?

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:

在此处输入图片说明

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM