代码之家  ›  专栏  ›  技术社区  ›  Manuel R

从矩阵中提取特定元素

  •  0
  • Manuel R  · 技术社区  · 7 年前

    假设我有一个矩阵

    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 回复  |  直到 7 年前
        1
  •  5
  •   Cath    7 年前

    可以使用参数 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"]]
    
        2
  •  2
  •   stas g    7 年前

    另一个解决方案是 row column 功能:

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

    至于这两种方法的速度,凯丝和我的:

    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
    

    Cath的平均速度稍快。