Become an expert in R — Interactive courses, Cheat Sheets, certificates and more!
Get Started for Free

encapsulate

Encapsulate Function Calls for Logging


Description

Evaluates a function while both recording an output log and measuring the elapsed time. There are currently three different modes implemented to encapsulate a function call:

  • "none": Just runs the call in the current session and measures the elapsed time. Does not keep a log, output is printed directly to the console. Works well together with traceback().

  • "evaluate": Uses the package evaluate to call the function, measure time and do the logging.

  • "callr": Uses the package callr to call the function, measure time and do the logging. This encapsulation spawns a separate R session in which the function is called. While this comes with a considerable overhead, it also guards your session from being teared down by segfaults.

Usage

encapsulate(
  method,
  .f,
  .args = list(),
  .opts = list(),
  .pkgs = character(),
  .seed = NA_integer_,
  .timeout = Inf
)

Arguments

method

(character(1))
One of "none", "evaluate" or "callr".

.f

(function())
Function to call.

.args

(list())
Arguments passed to .f.

.opts

(named list())
Options to set for the function call. Options get reset on exit.

.pkgs

(character())
Packages to load (not attach).

.seed

(integer(1))
Random seed to set before invoking the function call. Gets reset to the previous seed on exit.

.timeout

(numeric(1))
Timeout in seconds. Uses setTimeLimit() for "none" and "evaluate" encapsulation. For "callr" encapsulation, the timeout is passed to callr::r().

Value

(named list()) with three fields:

  • "result": the return value of .f

  • "elapsed": elapsed time in seconds. Measured as proc.time() difference before/after the function call.

  • "log": data.table() with columns "class" (ordered factor with levels "output", "warning" and "error") and "message" (character()).

Examples

f = function(n) {
  message("hi from f")
  if (n > 5) {
    stop("n must be <= 5")
  }
  runif(n)
}

encapsulate("none", f, list(n = 1), .seed = 1)

if (requireNamespace("evaluate", quietly = TRUE)) {
  encapsulate("evaluate", f, list(n = 1), .seed = 1)
}

if (requireNamespace("callr", quietly = TRUE)) {
  encapsulate("callr", f, list(n = 1), .seed = 1)
}

mlr3misc

Helper Functions for 'mlr3'

v0.10.0
LGPL-3
Authors
Michel Lang [cre, aut] (<https://orcid.org/0000-0001-9754-0393>), Patrick Schratz [aut] (<https://orcid.org/0000-0003-0748-6624>)
Initial release

We don't support your browser anymore

Please choose more modern alternatives, such as Google Chrome or Mozilla Firefox.