Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum every nth points

Tags:

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 
like image 939
Alex Avatar asked Mar 07 '13 07:03

Alex


1 Answers

unname(tapply(v, (seq_along(v)-1) %/% n, sum)) # [1] 55 155 255 355 455 555 655 755 855 955  
like image 93
Josh O'Brien Avatar answered Feb 18 '23 12:02

Josh O'Brien