I want to execute a R script in the background from the R console.
From the console , i usually run R script as source('~/.active-rstudio-document') I have to wait until the script is completed to go ahead with my rest of work. Instead of this i want R to be running in the background while i can continue with my work in the console. Also i should be somehow notified when R completes the source command. Is this possible in R ?
This might be quite useful as we often sees jobs taking long time.
PS - i want the source script to be running in the same memory space rather than a new one. Hence solutions like fork , system etc wont work for me. I am seeing if i can run the R script as a separate thread and not a separate process.
Use job::job() to run chunks of R code in an RStudio job instead of the console. This frees your console while the job(s) go brrrrr in the background. By default, the result is returned to the global environment when the job completes.
RStudio 1.2 introduced the ability to send long running R scripts to local and remote background jobs. This functionality can dramatically improve the productivity of data scientists and analysts using R since they can continue working in RStudio while jobs are running in the background.
The difference between running lines from a selection and invoking Source is that when running a selection all lines are inserted directly into the console whereas for Source the file is saved to a temporary location and then sourced into the console from there (thereby creating less clutter in the console).
You can run any R script in a separate session by pulling down the Source menu and choosing Source as Local Job. This will give you some options for running your job. By default, the job will run in a clean R session, and its temporary workspace will be discarded when the job is complete.
You can use system()
and Rscript to run your script as an asynchronous background process:
system("Rscript -e 'source(\"your-script.R\")'", wait=FALSE)
At the end of your script, you may save your objects with save.image()
in order to load them later, and notify of its completion with cat()
:
...
save.image("script-output.RData")
cat("Script completed\n\n")
Hope this helps!
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