Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R - Run source() in background

Tags:

r

background

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.

like image 647
Vineeth Mohan Avatar asked Jan 08 '13 05:01

Vineeth Mohan


People also ask

How do I run an R code in the background?

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.

Can R run in the background?

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.

What is the difference between Source and run in R?

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).

How do I run a local job in R?

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.


1 Answers

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!

like image 51
Theodore Lytras Avatar answered Oct 03 '22 01:10

Theodore Lytras