Let's say I have the array
TestArray=array(1:(3*3*4),c(3,3,4))
In the following I will refer to TestArray[i,,]
, TestArray[,j,]
and TestArray[,,k]
as the x=i
, y=j
and z=k
subsets, respectively. In this specific example, the indices i
and j
can go from 1 to 3 and k
from 1 to 4.
Now, I want to subset this 3 dimensional array so that I get the x=y
subset. The output should be
do.call("cbind",
list(TestArray[1,1,,drop=FALSE],
TestArray[2,2,,drop=FALSE],
TestArray[3,3,,drop=FALSE]
)
)
I have (naively) thought that such an operation should be possible by
library(Matrix)
TestArray[as.array(Diagonal(3,TRUE)),]
This works in 2 dimensions
matrix(1:9,3,3)[as.matrix(Diagonal(3,TRUE))]
However, in 3 dimensions it gives an error.
I know that I could produce an index array
IndexArray=outer(diag(1,3,3),c(1,1,1,1),"*")
mode(IndexArray)="logical"
and access the elements by
matrix(TestArray[IndexArray],nrow=4,ncol=3,byrow=TRUE)
But the first method would be much nicer and would need less memory as well. Do you know how I could fix TestArray[as.array(Diagonal(3,TRUE)),]
so that it works as desired? Maybe I am just missing some syntactic sugar...