[R] Access only part of last dimension of table/matrix

Jim Lemon jim at bitwrit.com.au
Sat Jul 2 09:58:07 CEST 2011

On 07/02/2011 07:50 AM, David Winsemius wrote:
> I would like to do some operations inside a function using only one
> value for the last dimension of a table/matrix:
> tabfn <- function (dfrm, facvec, YN ="event"){
> return( Etbl <- do.call(table, dfrm[ , c(facvec, "event") ]) )
> # just want Etbl[,,,"TRUE"] or Etbl[,, "TRUE"] or Etbl[,"TRUE"]
> }
> tbl <- tabfn(testdf, c("x", "y") )
> tbl # all value of event returned
> At the console it is easy for me to count the number of factors and use
> the right number of commas
> tbl[ , , "TRUE"] if I only want the slice with that value. How can I do
> this programmatically?

Hi David,
I used to do something like this before completely reprogramming the 
barNest function.

# set the first dimension (can be the last also) to a number "stat"
sliceargs[[1]] <- x[[stat]]
# for the rest of the dimensions of this array, tack on a comma
for (arg in 2:ndim) sliceargs[[arg]] <- TRUE
  sliceargs[[ndim + 1]] <- slice
# "slice" the array
xslice[[stat]] <- do.call("[", sliceargs)

To get the last dimension, just tack commas together for 1:(ndim-1) and 
then add the number at the end.
I think Bill Dunlap gave me this solution when I was struggling with it.


More information about the R-help mailing list