captureOutput

0th

Percentile

Evaluate an R expression and captures the output

Evaluate an R expression and captures the output.

Keywords
programming, IO
Usage
captureOutput(expr, file=NULL, append=FALSE, collapse=NULL, envir=parent.frame())
Arguments
expr

The R expression to be evaluated.

file

A file name or a connection to where the output is directed. Alternatively, if NULL the output is captured to and returned as a character vector.

append

If TRUE, the output is appended to the file or the (unopened) connection, otherwise it overwrites.

collapse

A character string used for collapsing the captured rows. If NULL, the rows are not collapsed.

envir

The environment in which the expression is evaluated.

Details

This method imitates capture.output with the major difference that it captures strings via a raw connection rather than via internal strings. The latter becomes exponentially slow for large outputs [1,2].

Value

Returns captured output as a character vector.

References

[1] R-devel thread 'capture.output(): Using a rawConnection() [linear] instead of textConnection() [exponential]?', 2014-02-03. https://stat.ethz.ch/pipermail/r-devel/2014-February/068349.html [2] JottR blog post 'PERFORMANCE: captureOutput() is much faster than capture.output()', 2015-05-26. http://www.jottr.org/2014/05/captureOutput.html

See Also

Internally, eval() is used to evaluate the expression. and capture.output to capture the output.

Aliases
  • captureOutput
Examples
# NOT RUN {
# captureOutput() is much faster than capture.output()
# for large outputs when capturing to a string.
for (n in c(10e3, 20e3, 30e3, 40e3)) {
  printf("n=%d\n", n)

  x <- rnorm(n)

  t0 <- system.time({
    bfr0 <- capture.output(print(x))
  })
  print(t0)

  t1 <- system.time({
    bfr <- captureOutput(print(x))
  })
  print(t1)
  print(t1/t0)

  bfr2n <- captureOutput(print(x), collapse="\n")
  bfr2r <- captureOutput(print(x), collapse="\r")

  stopifnot(identical(bfr, bfr0))
} # for (n ...)
# }
Documentation reproduced from package R.utils, version 2.8.0, License: LGPL (>= 2.1)

Community examples

Looks like there are no examples yet.