[R] building a subscript programatically
Rolf Turner
rolf.turner at xtra.co.nz
Wed Nov 2 01:10:09 CET 2011
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.
cheers,
Rolf Turner
More information about the R-help
mailing list