在R中进行子集操作/匹配行和列

4

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

> 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)

magic

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

许多感谢。
3个回答

6
这种神奇的操作被称为矩阵索引。如果你要排除的是行或列,或者矩阵索引允许使用负数值,那么操作会更加简单。
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

这两个都非常好。尤其是第二个。 - David Arenburg
1
矩阵索引是我最喜欢的 R 中未被充分利用的功能。 :) - Aaron left Stack Overflow

0

这里有一个可能的解决方案,不一定漂亮或高效。循环遍历每个单元格,如果它不在您原始坐标集中,则将其设置为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
    }
  }
}

0

有点巴洛克式:

    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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接