capture_all {svMisc} | R Documentation |
Run an R expression and capture output and messages in a similar way as it would be done at the command line
Description
This function captures results of evaluating one or several R
expressions the same way as it would be issued at the prompt in a R console.
The result is returned in a character string. Errors, warnings and other
conditions are treated as usual, including the delayed display of the
warnings if options(warn = 0)
.
Usage
capture_all(expr, split = TRUE, echo = TRUE, file = NULL, markStdErr = FALSE)
captureAll(expr, split = TRUE, echo = TRUE, file = NULL, markStdErr = FALSE)
warnings2(...)
Arguments
expr |
A valid R expression to evaluate (names and calls are also accepted). |
split |
Do we split output, that is, do we also issue it at the R console too, or do we only capture it silently? |
echo |
Do we echo each expression in front of the results (like in the
console)? In case the expression spans on more than 7 lines, only first and
last three lines are echoed, separated by |
file |
A file, or a valid opened connection where output is sunk. It
is closed at the end, and the function returns |
markStdErr |
If |
... |
Items passed directly to |
Value
Returns a string with the result of the evaluation done in the user workspace.
Note
If the expression is provided as a character string that should be
evaluated, and you need a similar behavior as at the prompt for incomplete
lines of code (that is, to prompt for more), you should not parse the
expression with parse(text = "<some_code>")
because it returns an error
instead of an indication of an incomplete code line. Use
parse_text("<some_code>")
instead, like in the examples bellow.
Of course, you have to deal with incomplete line management in your GUI/CLI
application... the function only returns NA
instead of a character string.
Starting from version 1.1.3, .Traceback
is not set any more in the base
environment, but it is .Traceback_capture_all
that is set in temp_env()
.
You can get its value with get_temp(".Traceback_capture_all")
.
Also, if there are many warnings, those are now assigned in temp_env()
instead of baseenv()
. Consequently, they cannot be viewer with warnings()
but use warnings2()
in this case.
See Also
parse()
, expression()
, capture.output()
Examples
writeLines(capture_all(expression(1 + 1), split = FALSE))
writeLines(capture_all(expression(1 + 1), split = TRUE))
writeLines(capture_all(parse_text("search()"), split = FALSE))
## Not run:
writeLines(capture_all(parse_text('1:2 + 1:3'), split = FALSE))
writeLines(capture_all(parse_text("badname"), split = FALSE))
## End(Not run)
# Management of incomplete lines
capt_res <- capture_all(parse_text("1 +")) # Clearly an incomplete command
if (is.na(capt_res)) cat("Incomplete line!\n") else writeLines(capt_res)
rm(capt_res)