Skip to content
Incomplete sheet

This sheet is incomplete and could use some attention. Please submit code snippet suggestions as an issue or PR here.

Parallel computation

Foreach package

For-each loop

Action Code Details
Sequential for-loop
foreach(i = 1:4) %do% {
    Sys.sleep(1)
}
Useful for debugging purposes
Parallel for-each loop
foreach(i = 1:4) %dopar% {
    Sys.sleep(4)
}
Combine results through concatenation
foreach(i=1:4, .combine=c) %dopar% {
    1
}
Post-process results
foreach(..., .final=as.integer)
Provide initial output object
lm0 = lm(y~x, data=dt)
foreach(i = 1:4, .init=lm0) %dopar% {
    lm(y~x, data=dt)
}
Saves time
Run loop in arbitrary order
foreach(..., .inorder=FALSE)
More efficient
Load packages needed by the for-loop body
foreach(..., .packages=c('data.table'))
Ignore and exclude errors from result
foreach(..., .errorhandling='remove')
Expose variable to for-loop body
foreach(..., .export=c('var'))
Exclude from export
foreach(..., .noexport=c('var'))
Verbose mode
foreach(..., .verbose=TRUE)

Register parallel back-end

Action Code Details
snow
library(snow)
library(doSNOW)
cl = makeCluster(detectCores()-1)
registerDoSNOW(cl)
Stop snow
stopCluster(cl)
snowfall
library(snowfall)
library(doSNOW)
sfInit(parallel=TRUE, cpus=detectCores()-1)
registerDoSNOW(sfGetCluster())
Stop snowfall
sfStop()
Check if a parallel back-end is registered
getDoParRegistered()
Unregister parallel back-end
registerDoSEQ()

Future package

Action Code Details
Create future
f = future({ 100 })
Apply a function to a list
future.apply::future_lapply(1:2, cat)
Check if a future has finished computation
resolved(f)
Get the computed value of a future (blocking)
value(f)
Get all futures from an environment or list
futures(results)
Retrieve result ignoring errors
result = tryCatch(x, error=function(e) NULL)

Run

Action Code Details
Run an expression
x %<-% { 100 }
x %<-% { 100 } y %<-% { 200 } x + y # blocks until results for x and y are in
Run expression with operator conflict from other package
future::`%<-%`(x, { 100 })
Run expression with a label
x %<-% { 100 } %label% 'math'
Run expression only once its value is requested
x %<-% { 100 } %lazy% TRUE
Run expression with seed
RNGkind("L'Ecuyer-CMRG")
x %<-% { rnorm(0, 1) } %seed% {set.seed(1); .Random.seed}
Run expressions and put results in list
results = listenv::listenv()
results[1] %<-% 200;
results[2] %<-% 300;