- Notifications
You must be signed in to change notification settings - Fork41
Call R from R
License
Unknown, MIT licenses found
Licenses found
r-lib/callr
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
Call R from R
It is sometimes useful to perform a computation in a separate R process,without affecting the current R process at all. This packages does exactlythat.
- Features
- Installation
- Synchronous, one-off R processes
- Background R processes
- Multiple background R processes and
poll() - Persistent R sessions
- Running
R CMDcommands - Configuration
- Code of Conduct
- Calls an R function, with arguments, in a subprocess.
- Copies function arguments to the subprocess and copies the returnvalue of the function back, seamlessly.
- Copies error objects back from the subprocess, including a stacktrace.
- Shows and/or collects the standard output and standard error of thesubprocess.
- Supports both one-off and persistent R subprocesses.
- Calls the function synchronously or asynchronously (in thebackground).
- Can call
R CMDcommands, synchronously or asynchronously. - Can call R scripts, synchronously or asynchronously.
- Provides extensible
r_process,rcmd_processandrscript_processR6 classes, based onprocessx::process.
Install the stable version from CRAN:
install.packages("callr")Install the development version from GitHub:
pak::pak("r-lib/callr")
User() to run an R function in a new R process. The results arepassed back seamlessly:
callr::r(function() var(iris[,1:4]))
You can pass arguments to the function by settingargs to the list ofarguments. This is often necessary as these arguments are explicitlycopied to the child process, whereas the evaluated function cannot referto variables in the parent. For example, the following does not work:
mycars<-carscallr::r(function() summary(mycars))
But this does:
mycars<-carscallr::r(function(x) summary(x),args=list(mycars))
Note that the arguments will be serialized and saved to a file, so ifthey are large R objects, it might take a long time for the childprocess to start up.
You can use any R package in the child process, just make sure to referto it explicitly with the:: operator. For example, the following codecreates anigraph graph in thechild, and calculates some metrics of it.
callr::r(function() {g<-igraph::sample_gnp(1000,4/1000);igraph::diameter(g) })
callr copies errors from the child process back to the main R session:
callr::r(function()1+"A")
.Last.errorThe error objects has two parts. The first belongs to the main process,and the second belongs to the subprocess.
.Last.error also includes a stack trace, that includes both the main Rprocess and the subprocess:
The top part of the trace contains the frames in the main process, andthe bottom part contains the frames in the subprocess, starting with theanonymous function.
By default, the standard output and error of the child is lost, but youcan request callr to redirect them to files, and then inspect the filesin the parent:
x<-callr::r(function() { print("hello world!"); message("hello again!") },stdout="/tmp/out",stderr="/tmp/err")readLines("/tmp/out")
readLines("/tmp/err")With thestdout option, the standard output is collected and can beexamined once the child process finished. Theshow = TRUE options willalso show the output of the child, as it is printed, on the console ofthe parent.
r_bg() is similar tor() but it starts the R process in thebackground. It returns anr_process R6 object, that provides a richAPI:
rp<-callr::r_bg(function() Sys.sleep(.2))rp
This is a list of allr_process methods:
ls(rp)These include all methods of theprocessx::process superclass and thenewget_result() method, to retrieve the R object returned by thefunction call. Some of the handiest methods are:
get_exit_status()to query the exit status of a finished process.get_result()to collect the return value of the R function call.interrupt()to send an interrupt to the process. This isequivalent to aCTRL+Ckey press, and the R process might ignoreit.is_alive()to check if the process is alive.kill()to terminate the process.poll_io()to wait for any standard output, standard error, or thecompletion of the process, with a timeout.read_*()to read the standard output or error.suspend()andresume()to stop and continue a process.wait()to wait for the completion of the process, with a timeout.
Multiple background R processes are best managed with theprocessx::poll() function that waits for events (standard output/erroror termination) from multiple processes. It returns as soon as oneprocess has generated an event, or if its timeout has expired. Thetimeout is in milliseconds.
rp1<-callr::r_bg(function() { Sys.sleep(1/2);"1 done" })rp2<-callr::r_bg(function() { Sys.sleep(1/1000);"2 done" })processx::poll(list(rp1,rp2),1000)
rp2$get_result()
processx::poll(list(rp1),1000)
rp1$get_result()
r_session is anotherprocessx::process subclass that represents apersistent background R session:
rs<-callr::r_session$new()rs
r_session$run() is a synchronous call, that works similarly tor(),but uses the persistent session.r_session$call() starts the functioncall and returns immediately. Ther_session$poll_process() method orprocessx::poll() can then be used to wait for the completion or otherevents from one or more R sessions, R processes or otherprocessx::process objects.
Once an R session is done with an asynchronous computation, itspoll_process() method returns"ready" and ther_session$read()method can read out the result.
rs<-callr::r_session$new()rs$run(function() runif(10))
rs$call(function() rnorm(10))rs
rs$poll_process(2000)
rs$read()
Thercmd() function calls anR CMD command. For example, you cancallR CMD INSTALL,R CMD check orR CMD config this way:
callr::rcmd("config","CC")
This returns a list with three components: the standard output, thestandard error, and the exit (status) code of theR CMD command.
CALLR_NO_TEMP_DLLS: Iftrue, then callr does not use a temporarydirectory to copy the client DLL files from, in the subprocess. Bydefault callr copies the DLL file that drives the callr subprocessinto a temporary directory and loads it from there. This is mainlyto avoid locking a DLL file in the package library, on Windows. Ifthis default causes issues for you, set it totrue, and then callrwill use the DLL file from the installed processx package. See also#273.
Please note that the callr project is released with aContributor Codeof Conduct. Bycontributing to this project, you agree to abide by its terms.
About
Call R from R
Topics
Resources
License
Unknown, MIT licenses found
Licenses found
Code of conduct
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.