I have a script with self-written functions (no plots). When I copy-paste that script into the R-Studio console, it takes ages to execute, but when I use source("Helperfunctions.R")
it doesn't take more than a second.
I am aware of two differences between running code via the source()
function vs. entering code at the R-Studio console:
From ?source
:
Since expressions are not executed at the top level, auto-printing is not done.
The way I understand this: source()
will not plot graphs (unless made specific with e.g. print(plot)
), while the R Studio console codes will always plot graphs. I'm sure this will affect the speed of execution to a certain degree, but this seems irrelevant in my case, because there are barely any plot calls.
And:
(...) the complete file is parsed before any of it is run
I have been working with R
for a while now, but I'm not sure whether this relevant for the speed-issue I'm having. Is it possible that completely parsing all code "before any of it is run" speeds up the execution of my helper functions script by a factor of a hundred?
Edit: I'm using R version 3.2.3.
The issue is not source()
vs. console line code. Instead, it is an issue of how RStudio sends code from the source pane to the console.
When I copy the content of Helperfunctions.R
and run it in RGui (instead of RStudio), the code is executed with nearly the same speed as when I use source("Helperfunctions.R")
in RStudio.
Apparently, lines of code always (?) require more execution time in RStudio than in RGui. Even though you may usually not notice the time-difference when executing a couple of lines in the console, it seems to make a huge difference when, say, 3.000 lines of code are being executed in the R Studio console at once.
My understanding is that upon using source("Helperfunctions.R")
in the RStudio source pane, the code is not actually sent to the RStudio console (which would have been slow), but is actually executed directly in the R
language.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With