[R] Indexing multi-dimensional table

William Dunlap wdunlap at tibco.com
Thu Dec 22 20:23:30 CET 2011


Continuing the annnoying tradition of partial quotes:
   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] 

You can build the 2nd argument to do.call with alist() instead
of list() to send missing arguments to the function given as
the 1st argument.  E.g. to extract the first row, as a row matrix,
from the matrix state.x77 you usually do
  > state.x77[1, , drop=FALSE]
          Population Income Illiteracy Life Exp Murder HS Grad Frost  Area
  Alabama       3615   3624        2.1    69.05   15.1    41.3    20 50708

and here are some unsucessful attempts to do it with do.call("[",...)
using list()):
  > do.call("[", list(state.x77, 1, ,drop=FALSE)) # bad
  Error in list(state.x77, 1, , drop = FALSE) : argument 3 is empty
  > do.call("[", list(state.x77, 1, drop=FALSE))
  [1] 3615

and a to do it with alist:
  > do.call("[", alist(state.x77, 1, ,drop=FALSE))
          Population Income Illiteracy Life Exp Murder HS Grad Frost  Area
  Alabama       3615   3624        2.1    69.05   15.1    41.3    20 50708

alist() produces a list that you can use c() and subscripting on
to add or modify arguments.  It is usually better to encapsulate
this sort of thing in a function like extract() that has a convenient
interface.

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com 

> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf Of davavra
> Sent: Thursday, December 22, 2011 10:31 AM
> To: r-help at r-project.org
> Subject: Re: [R] Indexing multi-dimensional table
> 
> 
> 
> >From help("[", package="base"): "An index value of NULL is treated as
> > if it were integer(0).".
> 
> Yeah, I should have read it better.
> 
> >I don't think there is an easy way to achieve:
> > y[,2:3,1,drop=FALSE]
> >  using do.call("[") without explicitly specify the indices for that
> > "missing" dimension, i.e.
>  ...
> >  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);
> 
> 
> Thanks, Henrik. I also wasn't aware of R.utils until today. I should do more
> reading :)
> 
>  DAV
> 
> 
> --
> View this message in context: http://r.789695.n4.nabble.com/Indexing-multi-dimensional-table-
> tp4224543p4226198.html
> Sent from the R help mailing list archive at Nabble.com.
> 
> ______________________________________________
> R-help at 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.



More information about the R-help mailing list