[R] building a subscript programatically

Ernest Adrogué nfdisco at gmail.com
Tue Nov 1 23:14:42 CET 2011


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?

Regards,
Ernest



More information about the R-help mailing list