Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This answer is an expanded version of my earlier comments which I have now deleted.</p> <p>zoo's <code>rollapply</code> already supports plain vectors and matrices. Furthermore its <code>rollapply</code> routine extracts the plain vectors or matrices from a zoo object before operating on it so there is no reason for a zoo object to take materially longer than a non-zoo object. The slowness you observed was a bug in <code>rollapply</code> (the extraction was not taking place properly) that was fixed in early November in the development version. This version is on R-Forge and installed like this:</p> <pre><code>install.packages("zoo", repo = "http://r-forge.r-project.org") </code></pre> <p>On the other hand, the generality of <code>rollapply</code> means its going to be much slower than special purpose routines or vectorized operations. </p> <p>zoo does have some specialized versions of <code>rollapply</code> (<code>rollmean</code>, <code>rollmedian</code>, <code>rollmax</code>) that are optimized for particular operations and will be much faster. If you can manufacture something out of those, e.g. a rolling sum of k terms is the same as <code>k</code> times a rolling mean, then you can get substantial speedups. Faster still will be manufacturing the rolling result from plain operations such as <code>+</code> .</p> <p>The post indicated that the function in question was just an example but the particular function could make a big difference in terms of speed since it will affect whether the sorts of speedups discussed are available.</p> <p>For example, running 3 replications of each of <code>rollapply</code>, <code>2 * rollmean</code> and a simple vectorized addition shows this:</p> <pre><code>&gt; library(zoo) &gt; library(rbenchmark) &gt; n &lt;- 10^4 &gt; set.seed(123) &gt; a &lt;- rnorm(n) &gt; library(rbenchmark) &gt; benchmark(rollapply = a1 &lt;- rollapplyr(a, 2, sum, fill = 0), + rollmean = a2 &lt;- 2 * rollmeanr(a, 2, fill = 0), + add = a3 &lt;- c(0, a[-1] + a[-n]), replications = 3, order = "relative") test replications elapsed relative user.self sys.self user.child sys.child 3 add 3 0.00 0.00000 0.00 0 NA NA 2 rollmean 3 0.07 1.00000 0.08 0 NA NA 1 rollapply 3 1.85 26.42857 1.84 0 NA NA &gt; &gt; all.equal(a1, a2) [1] TRUE &gt; all.equal(a1, a3) [1] TRUE </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload