How to apply a function to slices of multidimensional arrays, and not just iterating through single elements
well, you can still use apply(), e.g.,
A <- array(rnorm(3*4*5), c(3, 4, 5))
f <- sum
out <- numeric(4)
for (i in 1:4)
out[i] <- f(A[, i, ])
out
apply(A, 2, f)
I hope it helps.
Best,
Dimitris
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.
Dimitris Rizopoulos Assistant Professor Department of Biostatistics Erasmus University Medical Center Address: PO Box 2040, 3000 CA Rotterdam, the Netherlands Tel: +31/(0)10/7043478 Fax: +31/(0)10/7043014