【问题标题】:Sub-setting / Matching row and columns in RR中的子设置/匹配行和列
【发布时间】:2015-07-18 15:37:08
【问题描述】:

好的,所以我需要一个非常具体的子集公式。从矩阵 x 中,我只想保留由 rowscolumns 定义的元素。然后应该用零替换不需要的元素。示例如下:

> x <- matrix(c(65,46,52,76,34,345,65,87,12,53),nrow = 5,ncol = 2)
> x
     [,1] [,2]
[1,]   65  345
[2,]   46   65
[3,]   52   87
[4,]   76   12
[5,]   34   53

> rows <- c(1,1,2,3,3,4,5)
> cols <- c(1,2,2,1,2,1,2)

魔法

> x
     [,1] [,2]
[1,]   65  345
[2,]    0   65
[3,]   52   87
[4,]   76    0
[5,]    0   53

非常感谢

【问题讨论】:

    标签: r matrix match subset


    【解决方案1】:

    这种魔法称为矩阵索引。如果您不想要 rowscols,或者如果矩阵索引允许负值,那就更容易了。

    y <- matrix(0, nrow=5, ncol=2)
    y[cbind(rows,cols)] <- x[cbind(rows,cols)]
    y
    ##      [,1] [,2]
    ## [1,]   65  345
    ## [2,]    0   65
    ## [3,]   52   87
    ## [4,]   76    0
    ## [5,]    0   53
    

    或者,您可以“手动”执行相同的操作,并且可以使用负下标,因为知道矩阵可以被视为具有沿列索引的向量。

    k <- (cols-1)*nrow(x) + rows
    x[-k] <- 0
    x
    ##      [,1] [,2]
    ## [1,]   65  345
    ## [2,]    0   65
    ## [3,]   52   87
    ## [4,]   76    0
    ## [5,]    0   53
    

    【讨论】:

    • 这两个都很好。尤其是第二个。
    • 谢谢。矩阵索引是我最喜欢的 R 未充分利用的特性。:)
    【解决方案2】:

    这是一个可能的解决方案,不一定漂亮或有效。循环遍历每个单元格,如果它不在您的原始坐标集中,则将其设置为 0。

    x <- matrix(c(65,46,52,76,34,345,65,87,12,53),nrow = 5,ncol = 2)
    rows <- c(1,1,2,3,3,4,5)
    cols <- c(1,2,2,1,2,1,2)
    coords <- paste(rows,cols)
    numRows <- 5
    numCols <- 2
    for (i in 1:numRows){
      for (j in 1:numCols){
        if (!(paste(i,j) %in% coords)){
          x[i,j] <- 0
        }
      }
    }
    

    【讨论】:

      【解决方案3】:

      有点巴洛克风格:

          indicies <- NULL
          for (iter in 1:length(rows)) {
            indicies <- rbind(indicies, c(rows[iter], cols[iter]))
          }
      
          indicies
           [,1] [,2]
      [1,]    1    1
      [2,]    1    2
      [3,]    2    2
      [4,]    3    1
      [5,]    3    2
      [6,]    4    1
      [7,]    5    2
      
          y <- matrix(rep(0, 10), nrow=5, ncol=2)
          for (k in 1:nrow(indicies)) {
            y[indicies[k,1], indicies[k,2]] <- x[indicies[k,1], indicies[k,2]]
          }
          y
               [,1] [,2]
          [1,]   65  345
          [2,]    0   65
          [3,]   52   87
          [4,]   76    0
          [5,]    0   53
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-10-28
        • 2021-06-17
        • 1970-01-01
        • 2011-03-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多