[R] extract element, row, etc from general array structure
Thomas Lumley
tlumley at u.washington.edu
Mon Oct 29 17:29:19 CET 2001
On Mon, 29 Oct 2001, Jason Turner wrote:
> This one has me a bit stumped, and I know there may well be a really
> simple way of doing it in R. Sorry for the long-winded explanation.
>
> Short version:
> given an array of arbitrary number of dimensions D, how can we
> retrieve the Nth element of dimension D without knowing in
> advance what D will be? For example, given that array
> A has dimensions c(3,4,5), and N=2, can we write a function
> that will "know" to return A[,,2], and not mistake that
> for A[2] or A[,2]? Bonus question - can such a function
> be written without relying purely on an arbitrarily high
> number of "if" statements?
>
function(A,N){
dims<-dim(A)
D<-length(dims)
skip<-prod(dims[seq(length=D-1)])
slice<-A[ (N-1)*skip+1:skip]
if (D>1) dim(slice)<-dims[seq(length=D-1)]
return(slice)
}
-thomas
Thomas Lumley Asst. Professor, Biostatistics
tlumley at u.washington.edu University of Washington, Seattle
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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