Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vectorized sum over slices of an array

Tags:

arrays

r

Suppose I have an array of three dimensions:

set.seed(1)
foo <- array(rnorm(250),dim=c(5,10,5))

And I want to create a matrix of each row and layer summed over columns 4, 5 and 6. I can write do this like this:

apply(foo[,4:6,],c(1,3),sum)

But this splits the array per row and layer and is pretty slow since it is not vectorized. I could also just add the slices:

foo[,4,]+foo[,5,]+foo[,6,]

Which is faster but gets abit tedious to do manually for multiple slices. Is there a function that does the above expression without manually specifying each slice?

like image 471
Sacha Epskamp Avatar asked Jan 20 '23 07:01

Sacha Epskamp


1 Answers

I think you are looking for rowSums / colSums (fast implementations of apply)

colSums(aperm(foo[,4:6,], c(2,1,3)))

> all.equal(colSums(aperm(foo[,4:6,], c(2,1,3))), foo[,4,]+foo[,5,]+foo[,6,])
[1] TRUE
like image 95
Sameer Avatar answered Jan 30 '23 08:01

Sameer