虽然 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