# [R] Problem indexing into array

Ted Harding Ted.Harding at nessie.mcc.ac.uk
Sat Jul 19 12:34:01 CEST 2003

```Well, thanks to all who have come up with ideas and suggestions,
and commments about how R and S work, which I must consider!

Meanwhile, since it was beginning to appear that there might be
no direct method of doing it in R, I went down the same road as
Tony Plate's suggestion and gratefully adapted his template to
do what I needed. His function was called 'array.pos', to find
the location in an array of the element with given coordinates.
I'm seeking lots, so

marray.pos<-function(i,d){
sum(c(0,i-1)*c(1,cumprod(d[-length(d)]))) + (1:d) }

Example:
x<-array((1:144),dim=c(6,2,2,3,2))
t<-rbind(c(1,2,2,1),c(2,2,3,1),c(1,2,1,2),...)

Then the following returns a matrix with 6 columns, in which
each row consists of all the 6 values in x whose coordinates
[?,p,q,r,s] satisfy (p=1,q=2,r=2,s=1), then (p=2,q=2,r=3,s=1),
etc., until tthe rows of t are exhausted:

t(matrix(x[apply(t,1,marray.pos,dim(x))],ncol=nrow(t)))

Once again, an interesting thread, and thanks to all who took
part!

Ted.

```