I have what I thought would be a simple problem, but I haven't been able to find an appropriate answer. I have a multidimensional array v[x,y,z]
and I would like to apply a function to the array along the z dimension using a grouping variable (group). Here is an example (in R):
v<-1:81
dim(v)<-c(3,3,9)
group<-c('a','a','a','b','b','b','c','c','c')
Given that the grouping variable has 3 levels (a, b and c), the result (out) I'm looking for is an array of dimension 3x3x3. I can obtain out using the following code for the above example:
out1<-apply(v[,,c(1:3)],c(1,2),sum)
out2<-apply(v[,,c(4:6)],c(1,2),sum)
out3<-apply(v[,,c(7:9)],c(1,2),sum)
library(abind)
out<-abind(out1, out2, out3, along=3)
My question is if there is a a general means of obtaining the above result, which can be applied to large dimensional arrays and long grouping vectors.
raster
package, and thestack
andcalc
functions which are optimised for this kind of data.