12

Applying a function to a multidimensional array with a grouping variable

 3 years ago
source link: https://www.codesd.com/item/applying-a-function-to-a-multidimensional-array-with-a-grouping-variable.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Applying a function to a multidimensional array with a grouping variable

advertisements

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.


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))


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK