[R] How to apply a function to slices of multidimensional arrays, and not just iterating through single elements

Todor Kondic dolichenus at gmail.com
Fri Mar 6 11:50:43 CET 2009


Hello,

If I want to apply some f(x) to such chunks of the the array
dim(A)==c(d1,d2,d3,..,dk,...,dn) which are defined by A[...,ik,...]
(ik belongs to {1,..,dk}), for now I use iteration via 'for (i in
dim(A)[k]) f(A[...,k,...])' . Is there any more elegant approach, e.g
like in 'apply' function which you can use on margin of the array.
Just in my case I want the entire slice defined by margin to be an
argument to my f(x), not just element-by-element.

If the former is too confusing:
A - array
dim(A)=c(3,4,5)
f(x) - function; x is argument dim(x)=c(3,5)
A has 4 slices of dim c(3,5)
I want my result to be a vector c( f(A[,1,]), f(A[,2,]), f(A[,3,]), f(A[,4,]) )
Until now I was doing 'for (i in 1:4) res[i]<-f(A[,i,])' . Is there a
more efficient way of doing this, maybe some predefined function?

Cheers,

TK




More information about the R-help mailing list