Vectorized sum by slices of an array

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, summarized in columns 4, 5 and 6. I can write like this:

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

But this divides the array into a string and a layer and is rather slow since it is not vectorized. I could just add fragments:

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

It is faster, but it becomes difficult to do multiple trays manually. Is there a function that executes the above expression without manually specifying each slice?

+4
source share
2 answers

I think you are looking for rowSums / colSums (quick implementation 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 
+8
source

How about this:

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

I know that there are reasons to avoid parse , but I'm not sure how to avoid this in this case.

0
source

All Articles