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?
v = 1:100
n = 10
sidx = seq.int(from=1, to=length(v), by=n)
eidx = c((sidx-1)[2:length(sidx)], length(v))
thesum = sapply(1:length(sidx), function(i) sum(v[sidx[i]:eidx[i]]))
This gives:
thesum
[1] 55 155 255 355 455 555 655 755 855 955
Update
The olde version don't work. Here a ne awnser that use
rep
to create the grouping factor. No need to usecut
:You can use
tapply
or to get a list
EDIT
In case you have
1:92
, you can replace your cut by this :A little late to the party, but I don't see a
rowsum()
answer yet.rowsum()
is proven more efficient thantapply()
and I think it would also be very efficient relative to a few of the other responses as well.Using @Josh O'Brien's grouping technique would likely improve efficiency even more.
Simply wrap in
unname()
to drop the group names.