我试图在邻接矩阵中读取以图形方式创建网络 我可以用这个读取数据:
Matrix_One <- read.csv("Network Matrix.csv", header=TRUE)
Matrix <- as.matrix(Matrix_One)
first_network <- graph.adjacency(Matrix, mode= "directed", weighted=NULL)
但是这并没有承认第一列是标题,因为我收到了这条警告信息:
graph.adjacency.dense出错(adjmatrix,mode = mode,weighted = weighted,: 在structure_generators.c:273:非方矩阵,非方矩阵
知道如何让R读取column1作为标题吗?
答案 0 :(得分:0)
您想要删除Matrix的第一列,如下所示:
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
。