Chp
Chp

Reputation: 105

how to avoid for loop using apply function in this question

mat<-matrix(1:9,nrow=3,ncol=3)
for(i in 1:3){
  print(colSums(mat[1:i,]))
}

I'm trying to calculate mean of colSums of part of a matrix. enter image description here How do I avoid for loop in this case? The answer may be similar to the code below but I don't know how to proceed.

apply(mat,2,function(x) colSums(mat[]))

Thanks in advance!

Upvotes: 0

Views: 61

Answers (1)

dcarlson
dcarlson

Reputation: 11046

The simplest way is to use cumsum() to get the sums and rowMeans() to get the means:

apply(mat, 2, cumsum)[2:4, ]
#      [,1] [,2] [,3] [,4]
# [1,]    3   11   19   27
# [2,]    6   18   30   42
# [3,]   10   26   42   58
rowMeans(apply(mat, 2, cumsum)[2:4, ])
# [1] 15 24 34

Upvotes: 2

Related Questions