# [R] reverse array indexing

Peter Wolf s-plus at wiwi.uni-bielefeld.de
Thu Jul 31 12:00:05 CEST 2003

```Richard A. O'Keefe wrote:

>Jerome Asselin <jerome at hivnet.ubc.ca> suggests this:
>	arr <- array(rnorm(27),c(3,3,3))
>	dimarr <- dim(arr)
>	tmparr <- array(1:prod(dimarr),dimarr)
>	sapply(c(3),function(x,tmparr) which(tmparr==x,T),tmparr=tmparr)
>	sapply(c(3,17,13,5),function(x,tmparr) which(tmparr==x,T),tmparr=tmparr)
>
>Of course, in R we can simplify the last two lines to
>    sapply(<<argument goes here>>, function(x) which(tmparr==x,T))
>
>However, wearing my "computer scientist" hat, I have to wonder about costs.
>This is basically the equivalent of the APL "decode" operator.
>
>Let's define
>
>    index.decode <- function (index, array) {
>	dimarr <- dim(arr)
>	tmparr <- array(1:prod(dimarr), dimarr)
>	sapply(index, function(x) which(tmparr == x, T))
>    }
>
>The result is a matrix with C=length(index) columns
>and R=length(dim(array)) rows.  ...
>
>
I think you mean the APL encode operator?

> index<-1:8
> encode(index-1,c(2,2,2))+1
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,]    1    1    1    1    2    2    2    2
[2,]    1    1    2    2    1    1    2    2
[3,]    1    2    1    2    1    2    1    2