Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Expanding on my comment to chris_dubois's answer, here's some timing information:</p> <pre><code>&gt; system.time(res &lt;- rnorm(50000) - rnorm(50000)) user system elapsed 0.06 0.00 0.06 </code></pre> <p>Contrast this with fn3 from that same answer:</p> <pre><code>&gt; system.time(res3 &lt;- fn3(50000)) user system elapsed 1.33 0.01 1.36 </code></pre> <p>The first thing to notice is that my laptop is slower than chris_dubois's machine. :)</p> <p>The second, and more important, point is that the vector approach, quite applicable here, is an order of magnitude faster. (Also pointed out by Richie Cotton in a comment to the same answer).</p> <p>This brings me to the final point: it is a <strong>myth</strong> that <code>apply</code> and its friends are much faster than <code>for</code> loops in R. They're on the same order in most measurements I've seen. Because they're just <code>for</code> loops behind the scenes. See also this post:</p> <blockquote> <p><a href="http://yusung.blogspot.com/2008/04/speed-issue-in-r-computing-apply-vs.html" rel="nofollow noreferrer">http://yusung.blogspot.com/2008/04/speed-issue-in-r-computing-apply-vs.html</a></p> <p>According to Professor Brian Ripley, "apply() is just a wrapper for a loop." The only advantage for using apply() is that it makes your code neater!</p> </blockquote> <p>Exactly. You should use <code>apply</code> if it's more <em>expressive</em>, especially if you're programming in a functional style. Not because it's faster.</p>
 

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