在非方矩阵的矩阵中读取第一列为 header

Read first column as header in matrix for unsquare matrix

我正在尝试读取邻接矩阵以在图中创建网络 我可以用这个读取数据:

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

但这并没有确认第一列是 headers,因为我收到了这条警告消息:

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

知道如何让 R 将 column1 读取为 headers 吗?

您想像这样删除矩阵的第一列:

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

如果邻接矩阵的值是数字,建议使用 data.matrix() 而不是 as.matrix() 来获取矩阵中的数字值而不是字符串。通常邻接矩阵中的值是对应于作为数值给出的每个边缘权重的权重。

要让 R 将您的数据读取为可用的邻接矩阵,请考虑以下事项:

 # 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)

graph 已过时(我相信已从 CRAN 中删除)。上面的例子使用 igrpah 代替,这是一个综合的网络数据管理包,具有一些漂亮的可视化。上面代码的结果将是这样的:

如果您选择坚持 graph,您的点赞 first_network <- graph.adjacency(Matrix, mode= "directed", weighted=NULL) 也占方块 Matrix