从矩阵中提取特定元素

Man*_*l R 0 r matrix extraction

假设我有一个矩阵

x <- matrix(c(0, 1, 1,
              1, 0, 0,
              0, 1, 0), byrow = TRUE, nrow = 3, 
            dimnames = list(c("a", "b", "c"), c("a", "b", "c")))
Run Code Online (Sandbox Code Playgroud)

我现在需要两个向量(或者甚至是data.frame中更好的拖动列),第一个向量/列保存列名称,第二个向量保存rowname,其中所有元素x都是1.

所以在我的例子中我想得到这个

v1 <- c("a", "b", "b", "c")
v2 <- c("b", "a", "c", "a")
Run Code Online (Sandbox Code Playgroud)

对于20 x 20矩阵来说,这是最快和最优雅的方式.

Cat*_*ath 5

您可以使用以下参数arr.ind:

indices <- which(x==1, arr.ind=TRUE)
#  row col
#b   2   1
#a   1   2
#c   3   2
#a   1   3
Run Code Online (Sandbox Code Playgroud)

然后你可以用名称替换行/列索引:

v1 <- rownames(x)[indices[, "row"]]
v2 <- colnames(x)[indices[, "col"]]
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,'arr.ind`论点对我来说是新的.很有帮助! (2认同)