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