Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying a function to a multidimensional array with grouping variable

Tags:

r

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.

like image 890
Arhopala Avatar asked Apr 21 '13 20:04

Arhopala


People also ask

How do you calculate multidimensional array?

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.

Can a multidimensional array have more than 3 dimensions?

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.

Can we use multidimensional array in C?

In C programming, you can create an array of arrays. These arrays are known as multidimensional arrays. For example, float x[3][4];


1 Answers

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))
like image 166
flodel Avatar answered Oct 24 '22 02:10

flodel