[R] reverse array indexing
    Peter Dalgaard BSA 
    p.dalgaard at biostat.ku.dk
       
    Thu Jul 31 01:28:01 CEST 2003
    
    
  
"Buchsbaum, Brad (NIH/NIMH)" <BuchsbaB at intra.nimh.nih.gov> writes:
> Hi,
> 
> Suppose I have a multidimensional array:
> 
> tmp <- array(1:8, c(2,2,2))
> 
> is there a function out there that, given a one-dimensional array index,
> will
> return the separate indices for each array dimension?
> 
> for instance, tmp[8] is equivalent to tmp[2,2,2]. I'd like to derive the
> vector (2,2,2)
> from the index 8. 
One not very efficient way is this:
> foo <- seq(along=tmp)
> dim(foo)<-dim(tmp)
> which(foo==8,arr.ind=TRUE)
     dim1 dim2 dim3
[1,]    2    2    2
For more efficient solutions peek inside the code of which() and see
how it gets from ordinary indices to array indices using %% and %/%
operations. (Not very easy to grasp, I know).
-- 
   O__  ---- Peter Dalgaard             Blegdamsvej 3  
  c/ /'_ --- Dept. of Biostatistics     2200 Cph. N   
 (*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)             FAX: (+45) 35327907
    
    
More information about the R-help
mailing list