# [R] Indexing multi-dimensional table

David Winsemius dwinsemius at comcast.net
Thu Dec 22 16:35:24 CET 2011

```On Dec 21, 2011, at 10:34 PM, David A Vavra wrote:

> I want to take slices of a multi-dimensional table (or array) without
> knowing the number of dimensions in advance.
>
> As a test I tried using (in this example a 3d table):
>
>     do.call(`[`, list(tbl, x,NULL,NULL)]

Surely that was meant to be:

do.call(`[`, list(tbl, x,NULL,NULL) )

(This does imply you knew the number of dimensions was 3.)

>
> where I built the list on the fly. It works great as long as I only
> want the
> first dimension however when I try a different dimension, say with
> list(tbl,NULL,x,NULL), I get "<0 x 0> matrix" as the result. I
> thought this
> was because I wasn't calling the right function but there is no
> `[.table` or
> `[.matrix` or even `[.array`.

It is interesting to look at what that returns.

tbl <- array(1:27, c(3,3,3))
x=1

str( do.call(`[`, list(tbl, x,NULL,NULL) ) )
int[1, 0 , 0 ]

It looks as though the Nulls became 0's. So if you wanted to use
do.call(`[` then this succeeds:

> do.call(`[`, list(tbl, x, 1:dim(tbl)[2], 1:dim(tbl)[3]) )
[,1] [,2] [,3]
[1,]    1   10   19
[2,]    4   13   22
[3,]    7   16   25

As does this using the "empty comma" approach:

eval(parse(text= paste("tbl[ " ,x, " , , ]"))  )
[,1] [,2] [,3]
[1,]    1   10   19
[2,]    4   13   22
[3,]    7   16   25

(Which after looking at the `r.utils::extract` code suggested by
Bengtsson,  was what he did ....  after considerably better sanity
checking than above.)

>
>
> DAV
>
> 	[[alternative HTML version deleted]]

--

David Winsemius, MD
West Hartford, CT

```