【问题标题】:Print row and column for multiple elements in a matrix given that the indices鉴于索引,打印矩阵中多个元素的行和列
【发布时间】:2016-02-27 21:22:14
【问题描述】:

假设我有一个样本如下:

x <- matrix(sample(100,replace = TRUE), nrow = 10)

和一个包含我想访问的索引的向量,如下所示

indices <- c(22,23,55,2)

如何获取这些索引的行和列?

我想也许这会有所帮助

which(m == m[indices], arr.ind = TRUE)

但它只返回第一个索引。我假设我在那里做错了

【问题讨论】:

    标签: r


    【解决方案1】:
    > for (indices in unique(indices)){
    +       print(which(m == m[indices], arr.ind = TRUE))
    + }
         row col
    [1,]   4   1
    [2,]   2   7
    [3,]  10   8
    

    【讨论】:

      【解决方案2】:

      虽然 Hack-R 的解决方案很棒。如果 x 中的任何其他变量与 x[index]

      具有相同的值,它可能会为每个索引提供多个结果
      set.seed(100)
      x <- matrix(sample(100,replace = TRUE), nrow = 10)
      indices <- c(22,23,55,2)
      
      
      for (indices in unique(indices)){
             print(which(x == x[indices], arr.ind = TRUE))
       }
      
           row col
      [1,]   2   3
           row col
      [1,]   1   3
      [2,]   3   3
           row col
      [1,]   5   6
      [2,]   9   6
      [3,]   2   9
           row col
      [1,]   2   1
      [2,]   6   6
      

      这可能不是预期的行为。 此外,在每个循环中重置“索引”可能是不利的。

      一种解决方案是创建矩阵的临时副本。将除这些索引之外的所有值设置为零,然后进行比较以仅获取这些索引的位置。

      temp <- x
      temp[-(indices)] <- 0
      which(temp > 0, arr.ind = TRUE)
      
           row col
      [1,]   2   1
      [2,]   2   3
      [3,]   3   3
      [4,]   5   6
      

      注意:它以索引的递增顺序返回结果:

      sort(indices)
      [1]  2 22 23 55
      

      【讨论】:

        猜你喜欢
        • 2015-01-10
        • 1970-01-01
        • 2021-09-14
        • 2018-12-23
        • 1970-01-01
        • 2020-07-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多