captureOutput.Rd
Evaluate an R expression and captures the output.
captureOutput(expr, file=NULL, append=FALSE, collapse=NULL, envir=parent.frame())
The R expression to be evaluated.
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
.
If TRUE
, the output is appended to the file or
the (unopened) connection, otherwise it overwrites.
A character
string used for collapsing the captured
rows. If NULL
, the rows are not collapsed.
The environment
in which the expression is evaluated.
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].
Internally, eval
() is used to evaluate the expression.
and capture.output
to capture the output.
[1] R-devel thread 'capture.output(): Using a rawConnection() [linear] instead of textConnection() [exponential]?', 2014-02-04. 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. https://www.jottr.org/2014/05/26/captureoutput/
# 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 ...)
#> n=10000
#> user system elapsed
#> 0.016 0.000 0.016
#> user system elapsed
#> 0.007 0.000 0.007
#> user system elapsed
#> 0.4375 NaN 0.4375
#> n=20000
#> user system elapsed
#> 0.046 0.004 0.051
#> user system elapsed
#> 0.013 0.000 0.013
#> user system elapsed
#> 0.2826087 0.0000000 0.2549020
#> n=30000
#> user system elapsed
#> 0.09 0.00 0.09
#> user system elapsed
#> 0.018 0.000 0.018
#> user system elapsed
#> 0.2 NaN 0.2
#> n=40000
#> user system elapsed
#> 0.158 0.000 0.159
#> user system elapsed
#> 0.024 0.000 0.024
#> user system elapsed
#> 0.1518987 NaN 0.1509434