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

Domenico Vistocco vistocco at unicas.it
Fri Mar 6 12:09:19 CET 2009


If I well understand, maybe you have still apply at your disposal:

arrayA <- 1:60
dim(arrayA) <- c(3,4,5)
apply(arrayA, 2, sum)

You have the same result of:
res<-numeric(4);for (i in 1:4) res[i]<-sum(arrayA[,i,])

Ciao,
domenico

PS:
have a look at plyr package for more "slicing" and "applying" functions

Todor Kondic wrote:
> 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
>
> ______________________________________________
> 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