Sum Every N Values in Matrix

前端 未结 3 1415
余生分开走
余生分开走 2021-01-26 23:55

So I have taken a look at this question posted before which was used for summing every 2 values in each row in a matrix. Here is the link: sum specific columns among rows. I als

3条回答
  •  面向向阳花
    2021-01-27 00:19

    To sum consecutive sets of n elements from each row, you just need to write a function that does the summing and apply it to each row:

    n <- 3
    t(apply(y, 1, function(x) tapply(x, ceiling(seq_along(x)/n), sum)))
    #       1  2  3
    # [1,] 12 39 66
    # [2,] 15 42 69
    # [3,] 18 45 72
    

提交回复
热议问题