Irregular array subsetting in R -
let's have array
testarray=array(1:(3*3*4),c(3,3,4))
in following refer testarray[i,,]
, testarray[,j,]
, testarray[,,k]
x=i
, y=j
, z=k
subsets, respectively. in specific example, indices i
, j
can go 1 3 , k
1 4.
now, want subset 3 dimensional array x=y
subset. 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 such operation should 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 gives error.
i know produce index array
indexarray=outer(diag(1,3,3),c(1,1,1,1),"*") mode(indexarray)="logical"
and access elements by
matrix(testarray[indexarray],nrow=4,ncol=3,byrow=true)
but first method nicer , need less memory well. know how fix testarray[as.array(diagonal(3,true)),]
works desired? maybe missing syntactic sugar...
i don't know if abind::asub
(you) want. uses more efficient form of matrix indexing have above, still have coerce results right shape ...
indmat <- cbind(1:3,as.matrix(expand.grid(1:3,1:4))) matrix(testarray[indmat],nrow=4,ncol=3,byrow=true)
slightly more generally:
d <- dim(testarray)[1] d2 <- dim(testarray)[3] indmat <- cbind(1:d,as.matrix(expand.grid(1:d,1:d2)) matrix(testarray[indmat],nrow=d2,ncol=d,byrow=true)
Comments
Post a Comment