【问题标题】:Read first column as header in matrix for unsquare matrix读取第一列作为非方阵矩阵中的标题
【发布时间】:2018-05-17 10:28:17
【问题描述】:

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

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,模式 = 模式,加权 = 加权,: 在structure_generators.c:273:非方阵,非方阵

知道如何让 R 将 column1 作为标题读取吗?

【问题讨论】:

  • 请向我们展示您的 csv 文件的前三行以及 head(Matrix)dim(Matrix)
  • 糟糕,抱歉,它将第一行作为标题读取,但不是第一列。
  • “非方阵”是指您的矩阵的高度与宽度不同。比较 nrow(Matrix) 宽度 ncol(Matrix) 并查看第一列(可能包含垂直标题)如何使您的矩阵宽于高。

标签: r networking matrix igraph adjacency-matrix


【解决方案1】:

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

Matrix &lt;- 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 &lt;- graph.adjacency(Matrix, mode= "directed", weighted=NULL) 也将占据正方形Matrix

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-26
    • 1970-01-01
    • 1970-01-01
    • 2020-08-11
    • 1970-01-01
    • 1970-01-01
    • 2021-12-04
    相关资源
    最近更新 更多