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?
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.