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.
The total number of elements that can be stored in a multidimensional array can be calculated by multiplying the size of all the dimensions. For example: The array int x[10][20] can store total (10*20) = 200 elements. Similarly array int x[5][10][20] can store total (5*10*20) = 1000 elements.
Arrays can have more than one dimension. For example, the following declaration creates a two-dimensional array of four rows and two columns. int[,] array = new int[4, 2]; The following declaration creates an array of three dimensions, 4, 2, and 3.
In C programming, you can create an array of arrays. These arrays are known as multidimensional arrays. For example, float x[3][4];
Easy:
out <- apply(v, c(1, 2), by, group, sum)
But to get the data in exactly the same order as you want:
out <- aperm(apply(v, c(1, 2), by, group, sum), c(2, 3, 1))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With