[R] extract element, row, etc from general array structure

Peter Dalgaard BSA p.dalgaard at biostat.ku.dk
Sun Oct 28 13:06:32 CET 2001


Jason Turner <jasont at indigoindustrial.co.nz> writes:

> Since we don't know in advance how many dimensions foo will have,
> and the last dimension is the one we're interested in, how do
> we express in R:
>   if it's a vector, get foo[5],
>   if it's a matrix, get foo[,5],
>   if it's a 3d array, get foo[,,5], 
>   ...
> without being so ugly or having an arbitrary upper limit based on how
> many "if" statements I was prepared to type?
> 
> If there's no elegant way, I'll work around it by keeping records
> of data size, and pushing structures back to vectors when I 
> need to automatically pull segments of data out.  If there's an 
> easier way, I'd be most appreciative.


Something like this 

apply(foo, seq(length=length(dim(foo))-1),"[",5)

Won't work for vectors though since they don't have dim() and 1-D
arrays are probably also troublesome.

-- 
   O__  ---- Peter Dalgaard             Blegdamsvej 3  
  c/ /'_ --- Dept. of Biostatistics     2200 Cph. N   
 (*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)             FAX: (+45) 35327907
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list