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

时间:2015-02-18 01:46:20

标签: r algorithm matrix

我想知道从R中的邻接矩阵创建邻接列表的最快方法是什么。我目前正在使用for-for方法,但由于我必须处理大矩阵,因此最快的方法会有所帮助

示例矩阵:

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

预期的邻接清单:

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

以下是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)
})

非常感谢。

1 个答案:

答案 0 :(得分:4)

您可以将matrix视为table,并使用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

从这里开始,只需清理dimnames并重新排序您的输出,即可获得testthat所需的输出。

(或者,在第一行中使用upper.tri代替lower.tri,然后将列顺序更改为c(2, 1, 3)以获取正确的 order - 这可能比订购许多行更有效。)

相关问题