If for example I have a vector of numbers.
c(1:9)
Now, if I want to compute sum of three consecutive number in the following way:
(1+2+3,4+5+6,7+8+9)
how should I approach?
If for example I have a vector of numbers.
c(1:9)
Now, if I want to compute sum of three consecutive number in the following way:
(1+2+3,4+5+6,7+8+9)
how should I approach?
I learned to use this one correctly:
foo<-1:9
aggregate(foo,by=list(rep(1:3,each=3) ),FUN=sum)
For a longer input, do this:
function (x,len) aggregate(x,by=list(rep(1:(length(x)/len),each=len) ),FUN=sum)
And because I'm still waiting for what-if.xkcd.com to update, here's the timings: (and I did check that all calculate the right thing)
x<-1:99
len<-3
microbenchmark(shadow(x,len),rawr(x,len),groth(x,len),carl(x,len),times=10)
Unit: microseconds
expr min lq median uq max
shadow(x, len) 62.006 70.130 75.0480 97.926 180.884
rawr(x, len) 541.797 564.033 571.9445 585.842 639.295
groth(x, len) 514.002 525.548 547.5705 551.633 568.310
carl(x, len) 1045.536 1099.844 1120.5840 1166.553 1346.582
neval
10
10
10
10
So the matrix -- colSums
is fastest. I'll leave it to someone else to figure out the memory requirements of each approach.