[R] reverse array indexing

Patrick Burns pburns at pburns.seanet.com
Wed Jul 30 23:50:10 CEST 2003


I believe that the function below satisfies the request:

 rev.index <-
function (x, dims)
{
        ld <- length(dims)
        cumdim <- cumprod(dims)
        ans <- array(NA, c(length(x), ld))

        ans[, ld] <- (x-1) %/% cumdim[ld - 1] + 1
        ans[, ld-1] <- (x-1) %% cumdim[ld - 1] + 1

        if(ld > 2) {
                for(i in (ld-1):2) {
                        y <- ans[, i]
                        ans[, i] <- (y-1) %/% cumdim[i - 1] + 1
                        ans[, i-1] <- (y-1) %% cumdim[i - 1] + 1
                }
        }
        ans
}


Patrick Burns

Burns Statistics
patrick at burns-stat.com
+44 (0)20 8525 0696
http://www.burns-stat.com
(home of S Poetry and "A Guide for the Unwilling S User")

Buchsbaum, Brad (NIH/NIMH) wrote:

>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. 
>
>thanks,
>
>Brad Buchsbaum
>
>______________________________________________
>R-help at stat.math.ethz.ch mailing list
>https://www.stat.math.ethz.ch/mailman/listinfo/r-help
>
>
>  
>




More information about the R-help mailing list