Sum every nth points

前端 未结 9 1111
耶瑟儿~
耶瑟儿~ 2020-11-29 04:42

I have a vector and I need to sum every n numbers and return the results. This is the way I plan on doing it currently. Any better way to do this?



        
9条回答
  •  悲哀的现实
    2020-11-29 05:10

    One way is to convert your vector to a matric then take the column sums:

    colSums(matrix(v, nrow=n))
    [1]  55 155 255 355 455 555 655 755 855 955
    

    Just be careful: this implicitly assumes that your input vector can in fact be reshaped to a matrix. If it can't, R will recycle elements of your vector to complete the matrix.

提交回复
热议问题