[R] extract element, row, etc from general array structure
Jason Turner
jasont at indigoindustrial.co.nz
Sun Oct 28 12:03:10 CET 2001
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?
Long version:
I've been using Greg Warnes' wapply function (thanks Greg!),
and modifying it to suit my own ends. wapply() takes a vector,
and repeatedly applies a function FUNC (decided at run-time) to
windows of the data. The modification I've made is to generalize
the return structures - if a scalar is returned by FUNC, wapply
returns a vector. If FUNC gives a vector, wappaly returns a
matrix. etc...
A complementary function I'm trying to build is one that extracts
the results of FUNC for window N. As I see it, the logic would
be something like this:
if:
foo<-wapply(some.time.series, some.vector.returning.function)
foo is a matrix. The "extract" function would grab the column
of foo for window N. e.g. N=5, extract would return foo[,5]
(maybe even with classes set appropriately, if I get particularly
clever).
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.
Cheers
Jason
--
Indigo Industrial Controls Ltd.
64-21-343-545
jasont at indigoindustrial.co.nz
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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