从矩阵中提取特定元素

时间:2018-07-09 11:38:42

标签: 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")))

我现在需要两个向量(或者在data.frame中甚至更好的拖曳列),第一个向量/列保存着列名,第二个向量保存了x中所有元素为1的行名

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

v1 <- c("a", "b", "b", "c")
v2 <- c("b", "a", "c", "a")

对于20 x 20的矩阵,最快,最优雅的方法是什么。

2 个答案:

答案 0 :(得分:5)

您可以为此使用参数arr.ind

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

然后,您可以将行/列索引替换为名称:

v1 <- rownames(x)[indices[, "row"]]
v2 <- colnames(x)[indices[, "col"]]

答案 1 :(得分:2)

以及使用rowcolumn函数的另一个解决方案:

ind <- (x == 1)
colnames(x)[col(x)[ind]]
#[1] "a" "b" "b" "c"
rownames(x)[row(x)[ind]]
#[1] "b" "a" "c" "a"

关于Cath和我的两种方法的速度:

cath <- function(){
  x <- matrix(0, ncol = 20, nrow = 20, dimnames = list(letters[1 : 
 20], letters[1 : 20]))
  x[sample(20 * 20, rpois(1, 50))] <- 1
  indices <- which(x == 1, arr.ind = TRUE)
  list(v1 = rownames(x)[indices[, "row"]], v2 = colnames(x)[indices[, 
"col"]])
}


stas <- function(){
   x <- matrix(0, ncol = 20, nrow = 20, dimnames = list(letters[1 : 20], letters[1 : 20]))
   x[sample(20 * 20, rpois(1, 50))] <- 1
   ind <- (x == 1)
   list(v1 = colnames(x)[col(x)[ind]], v2 = rownames(x)[row(x)[ind]])
}

microbenchmark(cath, stas, times = 1000L)
# Unit: nanoseconds
# expr min lq   mean median uq  max neval
# cath  45 54 77.855   56.0 57 9718  1000
# stas  45 56 61.457   57.5 59 1831  1000

平均来说,洗个澡要快一点。

相关问题