Sum every nth points

前端 未结 9 1071
耶瑟儿~
耶瑟儿~ 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:13

    UPDATE:

    If you want to sum every n consecutive numbers use colSums
    If you want to sum every nth number use rowSums

    as per Josh's comment, this will only work if n divides length(v) nicely.

    rowSums(matrix(v, nrow=n))
     [1] 460 470 480 490 500 510 520 530 540 550
    
    colSums(matrix(v, nrow=n))
     [1]  55 155 255 355 455 555 655 755 855 955
    

提交回复
热议问题