# [R] Problem indexing into array

Peter Dalgaard BSA p.dalgaard at biostat.ku.dk
Sat Jul 19 00:05:11 CEST 2003

```[Argh. Forgot to cc: the list again...]

Ted Harding <Ted.Harding at nessie.mcc.ac.uk> writes:

> > mu[M[,1:3]]
> >
> > should do what you want, I think.  See chapter 1 of S Poetry.
> >
> > Patrick Burns
>
> Thanks Patrick (and honoured to hear from the author of S-Poetry!).
>
> This doesn't do what I want (I was probably not clear), though
> Tony Plate's reply looks promising if maybe cumbersome.
> (Thanks, Tony).
>
> Basically: Given that mu was made by
>
>   mu<-array(data=x, dim=c(9,2,2,2))
>
> say, where x has 72 reals in it, and given that the first three columns
> of M contain values (1 or 2) of p,q,r, I want to recover from mu
> the 9 values mu[,p,q,r] where (p,q,r) is the result of M[i,1:3] for
> some value of i.
>
> I don't want to do this as mu[,M[,1],M[,2],M[,3]] because in fact
> this is taking place inside a function where the dimensions of the
> arrays thrown at the function will not be known beforehand.
>
> And, if the result can be got for all rows of M in one swoop, instead
> of looping through the rows of M, all the better!

OK, you've suckered me in...

Let's see, this probably gets easier if you first do

aux <- array(1:8,c(2,2,2))
dim(mu) <- c(9,8)

then aux[M[,1:3]] will be a vector of numbers between 1 and 8 and

mu[,aux[M[,1:3]]

is what you want, I think. Another option would be along the lines of

apply(M[,1:3], function(r) do.call("[", c(alist(mu,), as.list(r)) )

where the use of alist() is a really filthy trick, but I know no other
way to insert a missing argument into do.call()...
--
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

```