开发者

Vectorized sum over slices of an array

开发者 https://www.devze.com 2023-03-17 10:32 出处:网络
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

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


How about this:

eval(parse(text=paste(sprintf('foo[,%i,]',4:6),collapse='+')))

I am am aware that there are reasons to avoid parse, but I am not sure how to avoid it in this case.

0

精彩评论

暂无评论...
验证码 换一张
取 消