如何在此问题中使用Apply函数避免for循环

时间:2019-12-19 05:23:54

标签: r performance for-loop apply

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

我正在尝试计算矩阵一部分的colSums的平均值。 enter image description here 在这种情况下,如何避免for循环?答案可能类似于下面的代码,但我不知道如何进行。

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

谢谢!

1 个答案:

答案 0 :(得分:1)

最简单的方法是使用cumsum()获取总和,使用rowMeans()获取均值:

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