% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/withDoRNG.R
\name{withDoRNG}
\alias{withDoRNG}
\title{Evaluates a foreach \verb{\%dopar\%} expression with the doRNG adapter}
\usage{
withDoRNG(expr, substitute = TRUE, envir = parent.frame())
}
\arguments{
\item{expr}{An R \link{expression}.}

\item{substitute}{(logical) If TRUE, \code{expr} is substituted, otherwise not.}

\item{envir}{The \link{environment} where to evaluate \code{expr}.}
}
\value{
The value of \code{expr}.
}
\description{
Evaluates a foreach \verb{\%dopar\%} expression with the doRNG adapter
}
\details{
This function is useful when there is a foreach \verb{\%dopar\%} expression that
uses the random-number generator (RNG).  Such code should ideally use
\verb{\%doRNG\%} of the \pkg{doRNG} package instead of \verb{\%dopar\%}.  Alternatively,
and second best, is if the code would temporarily register the \strong{doRNG}
foreach adapter.  If neither is done, then there is a risk that the
random numbers are not statistically sound, e.g. they might be correlated.
For what it is worth, the \strong{doFuture} adapter, which is set by
\code{\link[=registerDoFuture]{registerDoFuture()}}, detects when \strong{doRNG} is forgotten, and produces
an informative warning reminding us to use \strong{doRNG}.

If you do not have control over the foreach code, you can use
\code{withDoRNG()} to evaluate the foreach statement with
\code{doRNG::registerDoRNG()} temporarily set.
}
\section{Examples}{

Consider a function:

\if{html}{\out{<div class="sourceCode r">}}\preformatted{my_fcn <- function(n) \{
  y <- foreach(i = seq_len(n)) \%dopar\% \{
    stats::runif(n = 1L)
  \}
  mean(unlist(y))
\}
}\if{html}{\out{</div>}}

This function generates random numbers, but without involving \pkg{doRNG},
which risks generating poor randomness.  If we call it as-is, with the
\strong{doFuture} adapter, we will get a warning about the problem:

\if{html}{\out{<div class="sourceCode r">}}\preformatted{> my_fcn(10)
[1] 0.5846141
Warning message:
UNRELIABLE VALUE: One of the foreach() iterations ('doFuture-1')
unexpectedly generated random numbers without declaring so. There is a
risk that those random numbers are not statistically sound and the overall
results might be invalid. To fix this, use '\%dorng\%' from the 'doRNG'
package instead of '\%dopar\%'. This ensures that proper, parallel-safe
random numbers are produced. To disable this check, set option
'doFuture.rng.onMisuse' to "ignore".
>
}\if{html}{\out{</div>}}

To fix this, we use \code{withDoRNG()} as:

\if{html}{\out{<div class="sourceCode r">}}\preformatted{> withDoRNG(my_fcn(10))
[1] 0.535326
}\if{html}{\out{</div>}}
}

