Sum every nth points

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

    A little late to the party, but I don't see a rowsum() answer yet. rowsum() is proven more efficient than tapply() and I think it would also be very efficient relative to a few of the other responses as well.

    rowsum(v, rep(seq_len(length(v)/n), each=n))[,1]
    #  1   2   3   4   5   6   7   8   9  10 
    # 55 155 255 355 455 555 655 755 855 955
    

    Using @Josh O'Brien's grouping technique would likely improve efficiency even more.

    rowsum(v, (seq_along(v)-1) %/% n)[,1]
    #  0   1   2   3   4   5   6   7   8   9 
    # 55 155 255 355 455 555 655 755 855 955 
    

    Simply wrap in unname() to drop the group names.

提交回复
热议问题