Expanding on my comment to chris_dubois's answer, here's some timing information:
> system.time(res <- rnorm(50000) - rnorm(50000))
user system elapsed
0.06 0.00 0.06
Contrast this with fn3 from that same answer:
> system.time(res3 <- fn3(50000))
user system elapsed
1.33 0.01 1.36
The first thing to notice is that my laptop is slower than chris_dubois's machine. :)
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).
This brings me to the final point: it is a myth that apply
and its friends are much faster than for
loops in R. They're on the same order in most measurements I've seen. Because they're just for
loops behind the scenes. See also this post:
http://yusung.blogspot.com/2008/04/speed-issue-in-r-computing-apply-vs.html
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!
Exactly. You should use apply
if it's more expressive, especially if you're programming in a functional style. Not because it's faster.