withSink.Rd
Evaluate an R expression while temporarily diverting output.
withSink(expr, file, append=FALSE, type=c("output", "message"), substitute=TRUE,
envir=parent.frame())
The R expression to be evaluated.
A writable connection
or a character
string naming the
file to write to.
If TRUE
, the diverted output is appended to the file,
otherwise not.
A character
string specifying whether to divert output
sent to the standard output or the standard error.
See sink
() for details.
If TRUE
, argument expr
is
substitute()
:ed, otherwise not.
The environment
in which the expression should be evaluated.
Returns the results of the expression evaluated.
Upon exit (also on errors), this function will close the requested "sink". If additional sinks (of any type) where also opened during the evaluation, those will also be closed with a warning.
Internally, sink
() is used to divert any output.
# Divert standard output
pathname <- tempfile(fileext=".output.txt")
res <- withSink(file=pathname, {
print(letters)
})
mcat(readLines(pathname), sep="\n")
#> [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s"
#> [20] "t" "u" "v" "w" "x" "y" "z"
# Divert standard error/messages
pathname <- tempfile(fileext=".message.txt")
res <- withSink(file=pathname, type="message", {
mprint(LETTERS)
})
#> [1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S"
#> [20] "T" "U" "V" "W" "X" "Y" "Z"
mcat(readLines(pathname), sep="\n")
#>