I have a large array and I need to find the rowSums() for all the matrices within the array simultaneously, but individually. Whenever I do:
rowSums(array1[ , ,1:1000])
I get the total sum of all the values in each row across the entire array. What I need is:
rowSums(array1[ , ,1])
But that only gives me the rowSums() for 1 matrix and I need it for all of them. Essentially, I need to convert the array into a new array where the matrices are row sums of the previous matrices.
I could do it manually, but that would take me hours due to the size of the array and I know there is a simple solution I am to R-illiterate to see.
Thank you so much.
CodePudding user response:
We can use apply
with MARGIN = 3
apply(array1, 3, rowSums)
[,1] [,2] [,3]
[1,] 9 27 45
[2,] 12 30 48
which is the same as doing individually
> rowSums(array1[, , 1])
[1] 9 12
> rowSums(array1[, , 2])
[1] 27 30
> rowSums(array1[, , 3])
[1] 45 48
data
array1 <- array(1:18, c(2, 3, 3))