[R] General indexing in multidimensional arrays
Jannis
bt_jannis at yahoo.de
Thu Aug 4 22:38:48 CEST 2011
Thanks, Gene, for your hint! I indeed did not check any possible
situation and my function was not returning what I intened it to return.
This updated version, however, should. I am sure there are much easier
ways (or ready made functions) to do the same.
ind.datacube = function(
##title<< create logical index matrices for multidimensional datacubes
datacube ##<< array: datacube from which to extract the subparts
, logical.ind ##<< logical array: TRUE/FALSE index matrix for a
subset of the dimensions
## of datacube. The size of logical.ind`s dimesnions
has to match the
## sizes of the corresponding dimensions in datacube.
, dims='auto' ##<< integer vector or 'auto' : indices of the
dimensions in datacube corresponding
## to the dimensions of logical.ind. If set to
'auto' this matching is tried to
## be accomplished by comparing the sizes of the
dimensions of the two objects.
)
{
if (sum(logical.ind) == 0) {
stop('No TRUE value in index matrix!')
} else {
if (dims[1] == 'auto')
{
if (is.null(dim(logical.ind)[1])) {
size.ind = length(logical.ind)
logical.ind = matrix(logical.ind,ncol=1)
} else {
size.ind = dim(logical.ind)
}
dims = match(size.ind, dim(datacube))
if (sum(duplicated(size.ind)) > 0 || sum(duplicated(dims))
> 0 )
stop('dimensions do not match unambigously. Supply dims
manually!')
}
dims.all <- setdiff(1:length(dim(datacube)),dims)
ind.matrix.choice <- which(logical.ind, arr.ind = TRUE)
dims.all.expand <- list()
for (i in 1:length(dims.all))
dims.all.expand[[i]] <- 1:dim(datacube)[dims.all[i]]
dims.all.grid <- as.matrix(do.call(expand.grid,
dims.all.expand))
expgrid.dims.all <- as.matrix(do.call(expand.grid,
dims.all.expand))
dims.all.mat <-
matrix(rep(dims.all.grid,times=2),ncol=length(dims.all))
ind.matrix.all <-
cbind(ind.matrix.choice[rep(1:dim(ind.matrix.choice)[1],each=dim(dims.all.grid)[1]),]
,
dims.all.mat)
ind.matrix.ord <- ind.matrix.all[,order(c(dims,dims.all))]
}
colnames(ind.matrix.ord) <- paste('dim',1:length(dim(datacube)),sep='')
##value<< integer index matrix which can be used to index datacube
ind.matrix.ord
}
data <- array(rnorm(64),dim=c(4,4,4))
indices <- matrix(FALSE,ncol=4,nrow=4)
indices[1,3] <- TRUE
indices[4,1] <- TRUE
#result <- data[indices,]
ind.datacube(data, indices, dims=c(1,2))
On 08/04/2011 09:20 PM, Gene Leynes wrote:
> data<- array(rnorm(64),dim=c(4,4,4))
More information about the R-help
mailing list