withCapture.RdEvaluates an expression and captures the code and/or the output.
withCapture(expr, replace=getOption("withCapture/substitute", ".x."), code=TRUE,
output=code, ..., max.deparse.length=getOption("max.deparse.length", 10000), trim=TRUE,
newline=getOption("withCapture/newline", TRUE), style=getOption("withCapture/style",
"console"), collapse="\n", envir=parent.frame())The R expression to be evaluated.
An optional named list used for substituting
symbols with other strings.
If TRUE, the deparsed code of the expression is echoed.
If TRUE, the output of each evaluated subexpression
is echoed.
Additional arguments passed to sourceTo
which in turn passes arguments to source().
A positive integer specifying the maximum
length of a deparsed expression, before truncating it.
If TRUE, the captured rows are trimmed.
If TRUE and collapse is non-NULL, a newline
is appended at the end.
A character string specifying the format of the
captured rows. If "console" (default), the code is echoed
as in an interactive R session, that is, each line of code is
prefixed with the R prompt (getOption("prompt") and
getOption("continue")), and the output is left as is.
If "script", the code is echoed as is, without any prompts,
and each line of output is prefixed with "#> ", which
makes the result suitable for copy-and-pasting into R.
This argument cannot be combined with arguments prompt.echo
and continue.echo passed via ....
A character string used for collapsing the captured
rows. If NULL, the rows are not collapsed.
The environment in which the expression is evaluated.
Returns a character string class 'CapturedEvaluation'.
Internally, eval() is used to evaluate the expression.
print(withCapture({
n <- 3
n
for (kk in 1:3) {
printf("Iteration #%d\n", kk)
}
print(Sys.time())
type <- "horse"
type
}))
#> > n <- 3
#> > n
#> [1] 3
#> > for (kk in 1:3) {
#> + printf("Iteration #%d\n", kk)
#> + }
#> Iteration #1
#> Iteration #2
#> Iteration #3
#> > print(Sys.time())
#> [1] "2026-11-11 17:11:25 PST"
#> > type <- "horse"
#> > type
#> [1] "horse"
## > n <- 3
## > n
## [1] 3
## > for (kk in 1:3) {
## + printf("Iteration #%d\n", kk)
## + }
## Iteration #1
## Iteration #2
## Iteration #3
## > print(Sys.time())
## [1] "2011-11-06 11:06:32 PST"
## > type <- "horse"
## > type
## [1] "horse"
# Automatic "variable" substitute
# (disable with relabel=NULL)
a <- 2
b <- "Hello world!"
print(withCapture({
x <- .a.
s <- .b.
x
s
}))
#> > x <- 2
#> > s <- "Hello world!"
#> > x
#> [1] 2
#> > s
#> [1] "Hello world!"
## > x <- 2
## > s <- "Hello world!"
## > x
## [1] 2
## > s
## [1] "Hello world!"