Multi-Core Replicate

Multi-core replication function to make it easier to do fast Monte Carlo simulation. Based on the mcreplicate() function from the 'rethinking' package. The 'rethinking' package requires installing 'rstan', which is onerous to install, while also not adding capabilities to this function.


mcreplicate: Multi-Core Replications

R-CMD-check Codecov testcoverage Lifecycle:stable

mcreplicate adds multi-core functionality to R’s replicate function. It allows easy parallelization on all platforms, including on Windows.

Installation

Install the package from GitHub:

if (!require(remotes)) install.packages("remotes")
remotes::install_github("christophergandrud/mcreplicate")

Use

mc_replicate() works just like replicate(), but distributes the replications on multiple cores

library(mcreplicate)

# Function to replicate
one_sim <- function(n = 100, control_prob = 0.1, rel_effect = 0.01) {
  treat_prob <- control_prob + (control_prob * rel_effect)
    
  cy <- rbinom(n = n, size = 1, prob = control_prob)
  ty <- rbinom(n = n, size = 1, prob = treat_prob)
  
  mean(ty) - mean(cy)
}

mc_replicate(10, one_sim())
##  [1] -0.04  0.10 -0.02 -0.02  0.05 -0.02 -0.01 -0.07 -0.05  0.00

Windows users

On Windows, mcreplicate relies on a parallel socket cluster backend. This requires the user to explicitly specify which packages and variables should be used to populate the workers’ environments. By default, mcreplicate attaches all currently loaded packages and all variables from the current environment which do not start with a “.”. This can be changed using the packages, varlist and envir optional arguments. You can learn more on the function’s help file.

Example

k = 2

# The following works as intended since the variable "k" is exported by 
# default to each worker.
mc_replicate(10, rnorm(k))

# For a reduced overhead, you can specify to *only* export the variable "k" 
# from the current environment and to not load any particular package.
mc_replicate(10, rnorm(k), packages = NULL, varlist = c("k"), 
             envir = environment())

References

This is inspired by the mcreplicate function from the rethinking package. We added Windows support and we provide a lightweight package.

Reference manual

It appears you don't have a PDF plugin for this browser. You can click here to download the reference manual.

install.packages("mcreplicate")

0.1.2 by Christopher Gandrud, 5 years ago


Browse source code at https://github.com/cran/mcreplicate


Authors: Christopher Gandrud [aut, cre] , Olivier Binette [ctb] , AUTUMN41 [ctb]


Documentation:   PDF Manual  


AGPL (>= 3) license


Imports parallel

Suggests testthat, covr


See at CRAN