R: Run an R expression and capture output and messages in a...

captureAll {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

    captureAll(expr, split = TRUE, echo = TRUE, file = NULL, markStdErr = FALSE)

### 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 sinked. It is closed at the end, and the function returns `NULL` in this case. If `file = NULL` (by default), a textConnection() captures the output and it is returned is a character string by the function.
`markStdErr` | if `TRUE`, stderr is separated from sddout by STX/ETX character

### 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 behaviour as at the prompt for incomplete lines of code (that is, to prompt for more), you should not parse the expression with `parse(text = "<mycode>")` because it returns an error instead of an indication of an incomplete code line. Use `parseText("<mycode>")` 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.

### Author(s)

Philippe Grosjean (phgrosjean@sciviews.org)

### See Also

`parseText`, `parse`, `expression`, `capture.output`, `sourceClipboard`

### Examples

    writeLines(captureAll(expression(1+1), split = FALSE))
    writeLines(captureAll(expression(1+1), split = TRUE))
    writeLines(captureAll(parseText("search()"), split = FALSE))

    ## Not run:
    writeLines(captureAll(parseText('1:2 + 1:3'), split = FALSE))
    writeLines(captureAll(parseText("badname"), split = FALSE))

    ## End(Not run)

    ## Management of incomplete lines
    captRes <- captureAll(parseText("1 +")) # Clearly an incomplete command
    if (is.na(captRes)) cat("Incomplete line!\n") else writeLines(captRes)
    rm(captRes)

[Package svMisc version 0.9-70 Index]