[R] building a subscript programatically

Ernest Adrogué eadrogue at gmx.net
Wed Nov 2 01:43:04 CET 2011


 2/11/11 @ 13:10 (+1300), Rolf Turner escriu:
> On 02/11/11 11:14, Ernest Adrogué wrote:
> >Hi,
> >
> >On ocasion, you need to subscript an array that has an arbitrary
> >(ie. not known in advance) number of dimensions. How do you deal with
> >these situations?
> >It appears that it is not possible use a list as an index, for
> >instance this fails:
> >
> >>x<- array(NA, c(2,2,2))
> >>x[list(TRUE,TRUE,2)]
> >Error in x[list(TRUE, TRUE, 2)] : invalid subscript type 'list'
> >
> >The only way I know is using do.call() but it's rather ugly. There
> >must be a better way!!
> >
> >>do.call('[', c(list(x), TRUE, TRUE, 2))
> >      [,1] [,2]
> >[1,]   NA   NA
> >[2,]   NA   NA
> >
> >Any idea?
> 
> It's possible that matrix subscripting might help you.  E.g.:
> 
>  a <- array(1:60,dim=c(3,4,5))
>  m <- matrix(c(1,1,1,2,2,2,3,4,5,1,2,5),byrow=TRUE,ncol=3)
>  a[m]
> [1]  1 17 60 52
> 
> You can build "m" to have the same number of columns as your array
> has dimensions.
> 
> It's not clear to me what result you want in your example.

Sorry for not stating my problem in a more clear way. What I want is,
given an array of n dimensions, overwrite it by iteratating over its
"outermost" dimension... OK, in the previous example, I would like
to do

x <- array(NA, c(2,2,2))
for (i in 1:2) {
    x[,,i] <- 0
}

As you can see, the index I used in the loop only works in the case of
three-dimensional arrays, if x was two dimensional I would have had to
write 

for (i in 1:2) {
    x[,i] <- 0
}

So, when the dimensions of x are not known in advance, how would you
write such a loop?
Your solution of using a matrix might work (I haven't been able to
check it yet).

Cheers,
Ernest



More information about the R-help mailing list