考虑这个数组:
the.seq <- 1:4
sol<- outer(outer(the.seq, the.seq, `+`), the.seq, `+`)
我想找到所有和6的元素。这对于which
非常容易:
indices <- which(sol == 6)
indices
[1] 4 7 10 13 19 22 25 34 37 49
现在我想要一个带有这些元素的维度索引的向量,答案是:
[,1] [,2] [,3]
[1,] 4 1 1
[2,] 3 2 1
[3,] 2 3 1
[4,] 1 4 1
[5,] 3 1 2
[6,] 2 2 2
[7,] 1 3 2
[8,] 2 1 3
[9,] 2 1 3
[10,] 1 1 4
你会怎么做?
答案 0 :(得分:3)
您可以使用arr.ind
中的which
参数。设置为TRUE
时,which
将返回其第一个参数为TRUE
的数组索引。
which(sol == 6, arr.ind = TRUE)
# dim1 dim2 dim3
# [1,] 4 1 1
# [2,] 3 2 1
# [3,] 2 3 1
# [4,] 1 4 1
# [5,] 3 1 2
# [6,] 2 2 2
# [7,] 1 3 2
# [8,] 2 1 3
# [9,] 1 2 3
#[10,] 1 1 4