On Thu, Dec 22, 2011 at 4:34 AM, David A Vavra <dava...@verizon.net> 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)] > > > > 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`. > > > > Am I going about this the wrong way?
>From help("[", package="base"): "An index value of NULL is treated as if it were integer(0).". > y <- array(1:24, dim=c(2,3,4)) > dimnames(y)[[1]] <- sprintf("a%d", 1:dim(y)[1]) > dimnames(y)[[2]] <- sprintf("b%d", 1:dim(y)[2]) > dimnames(y)[[3]] <- sprintf("c%d", 1:dim(y)[3]) > y[NULL,2:3,1,drop=FALSE] , , c1 b2 b3 > y[integer(0),2:3,1,drop=FALSE] , , c1 b2 b3 I don't think there is an easy way to achieve: > y[,2:3,1,drop=FALSE] , , c1 b2 b3 a1 3 5 a2 4 6 using do.call("[") without explicitly specify the indices for that "missing" dimension, i.e. > y[seq(length=dim(y)[1]),2:3,1,drop=FALSE] , , c1 b2 b3 a1 3 5 a2 4 6 If you're willing to use R.utils you can do: library("R.utils"); > extract(y, indices=list(2:3,1), dims=c(2,3), drop=TRUE); b2 b3 a1 3 5 a2 4 6 My $.02 /Henrik > > > > DAV > > > > > [[alternative HTML version deleted]] > > ______________________________________________ > R-help@r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code. ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.