简体   繁体   English

如何在邻接表中转换对称矩阵?

[英]How to convert a symmetric matrix in an adjacency list?

I would like to know what is the fastest way to create an adjacency list from an adjacency matrix in R. I am currently using a for-for approach, but as I have to deal with big matrices a fastest approach would be helpful. 我想知道从R中的邻接矩阵创建邻接表的最快方法是什么。我目前正在使用for-for方法,但是由于我必须处理大型矩阵,所以最快的方法会有所帮助。

An example matrix: 矩阵示例:

  A B C D
A 1 2 3 4
B 2 1 2 3
C 3 2 1 2
D 4 3 2 1

The expected adjacency list: 预期的邻接表:

A B 2
A C 3 
A D 4
B C 2
B D 3
C D 2

Below is a testthat test that covers my current code: 下面是一个testthat覆盖我当前的代码测试:

test_that("Matrix to List", {
  mat <- matrix(c(1,2,3,4,
                  2,1,2,3,
                  3,2,1,2,
                  4,3,2,1), ncol=4)
  colnames(mat) <- rownames(mat) <- letters[1:4]
  adj <- matrixToAdjacencyList(mat)
  expected <- data.frame(Columns=c("a", "a", "a", "b", "b", "c"),
                            Rows=c("b", "c", "d", "c", "d", "d"),
                           Value=c(2,3,4,2,3,2))
  expect_identical(adj, expected)
})

Thanks a lot. 非常感谢。

You can treat your matrix like a table and use the data.frame method. 您可以将matrixtable一样对待,并使用data.frame方法。

mat[lower.tri(mat, diag = TRUE)] <- NA
na.omit(data.frame(as.table(mat)))
#    Var1 Var2 Freq
# 5     A    B    2
# 9     A    C    3
# 10    B    C    2
# 13    A    D    4
# 14    B    D    3
# 15    C    D    2

From here, it's just a matter of cleaning up your dimnames and reordering your output to get your exact desired output for your testthat . 从这里开始,只需清理您的dimnames并对输出进行重新排序,以获取您的testthat所需的确切输出。

(Or, use upper.tri instead of lower.tri in the first line, and then it's a matter of changing the column order to c(2, 1, 3) to get the right column order--that might be more efficient than ordering many rows.) (或者,在第一行中使用upper.tri而不是lower.tri ,然后就可以将列顺序更改为c(2, 1, 3) lower.tri c(2, 1, 3)以获得正确的顺序,这可能比订购许多行。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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