capture: Capture Evaluation Side Effects

View source: R/capture.R

captureR Documentation

Capture Evaluation Side Effects

Description

This function evaluates an R expression while capturing its printed output, messages, warnings, and errors. It returns a list containing the result of the evaluation along with all the captured texts.

Usage

capture(expr)

Arguments

expr

An R expression to evaluate. The expression is captured using substitute() to retain its code form before evaluation.

Details

The function uses withCallingHandlers() and tryCatch() to capture side effects of evaluating the expression. Printed output is captured using capture.output(). Warnings and messages are intercepted and their default display is suppressed using invokeRestart("muffleWarning") and invokeRestart("muffleMessage"), respectively. If an error occurs, its message is stored and NULL is returned as the value.

Value

A list with the following components:

value

The result of evaluating expr.

output

A character vector with the printed output produced during evaluation.

messages

A character vector with any messages generated during evaluation.

warnings

A character vector with any warnings produced during evaluation.

error

A character string with the error message if an error occurred; otherwise NULL.

Examples

## Not run: 
  # Example: Capturing output, messages, warnings, and errors
  captured <- capture({
    print("Hello, world!")
    message("This is a message.")
    warning("This is a warning.")
    42  # Final value returned
  })

  # Display the captured components
  print(captured$output)    # Printed output
  print(captured$messages)   # Messages
  print(captured$warnings)   # Warnings
  print(captured$error)      # Error message (if any)
  print(captured$value)      # The evaluated result (42 in this example)

## End(Not run)


h2otools documentation built on April 4, 2025, 2:33 a.m.