An embedded and charset-unspecified text was scrubbed... Name: not available URL: <https://stat.ethz.ch/pipermail/r-help/attachments/20080910/88f65ddf/attachment.pl>
Return dimension index from array with n-dimensions
2 messages · Hintzen, Niels, jim holtman
Is this what you were looking for:
a <- array(100:1,dim=c(5,4,5)) which(a == 7)
[1] 94
which(a == 7, arr.ind=TRUE)
dim1 dim2 dim3 [1,] 4 3 5
On Wed, Sep 10, 2008 at 10:22 AM, Hintzen, Niels <Niels.Hintzen at wur.nl> wrote:
Hi,
I have been dealing with some problems finding a fast way of getting to
know in what dimension a specific value is located out of an array (like
the 'which' function for a vector returns its position).
Unable to find anything about this on the internet I wrote a function
myself.
Could you please comment if such a function already exists, and if not,
please feel free to comment the function I wrote.
Hopefully resulting in the integration of such a function in a
R-packages.
Kind regards,
Niels Hintzen
#Example:
a <- array(100:1,dim=c(5,4,5))
which(a == 7)
nindex(a,7)
nindex<-function(array.,index.){
dims <- dim(array.)
ldim <- length(dim(array.))
dimmy <- matrix(NA,ncol=length(index.),nrow=ldim)
remain <- matrix(NA,ncol=length(index.),nrow=ldim)
remain[1,] <- index.
for(i in 1:(length(dims)-1)){
dimmy[i,] <-
ceiling(remain[i,]/(prod(dims[1:(ldim-i)])))
dimmy[i,dimmy[i,]==0] <- rev(dims)[i]
remain[i+1,] <- index.%%prod(dims[1:(ldim-i)])
}
remain[length(remain[,1]),remain[length(remain[,1]),]==0]
<- dims[1]
dimmy[1+(length(dims)-1),] <- remain[length(remain[,1]),]
dimmy <- dimmy[dim(dimmy)[1]:1,]
return(matrix(t(dimmy),nrow=length(index.),dimnames=list(seq(1,length(in
dex.),1),dimensions=paste("dim",as.character(c(1:length(dims))),sep=""))
))}
[[alternative HTML version deleted]]
______________________________________________ R-help at r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
Jim Holtman Cincinnati, OH +1 513 646 9390 What is the problem that you are trying to solve?