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
I will add one more way of doing it without any function from
apply
familyOne way is to convert your vector to a matric then take the column sums:
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.
One way is to use
rollapply
fromzoo
:And in case
length(v)
is not a multiple ofn
:Here are some of the main variants offered so far
Basic test cases might be
f0
fails with the final test, but this could probably be fixedThe cumsum approach
f3
is subject to rounding error, and the presence of an NA early inv
'poisons' later resultsIn terms of performance, the original solution is not bad
but the matrix solution
f2
seems to be both fast and flexible (e.g., adjusting the handling of that trailing chunk of fewer thann
elements)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
divideslength(v)
nicely.