This is a follow-up question to Convert a message to a character vector, asked yesterday. I am developing a function that returns the outputted message (if any) from a function call as a character vector. I'd like to make it general, in that in the following functions, FUN
is a function, arg
or arg1
is the first argument, and ...
are the further arguments. This first function works well.
getMessage <- function(FUN, arg)
{
FUN <- deparse(substitute(FUN))
tc <- textConnection("messages", "w")
on.exit(close(tc))
sink(tc, type = "message")
eval(call(FUN, arg))
sink(NULL, type = "message")
messages
}
getMessage(scan, "data.txt")
# [1] "Read 15 items"
But when I add ...
, to be able to generalize it to other function calls, I get no output and the "messages"
connection remains open.
getMessage <- function(FUN, arg1, ...)
{
FUN <- deparse(substitute(FUN))
tc <- textConnection("messages", "w")
on.exit(close(tc))
sink(tc, type = "message")
eval(call(FUN, arg1, ...))
sink(NULL, type = "message")
messages
}
> getMessage(scan, "data.txt")
> showConnections()
# description class mode text isopen can read can write
# 3 "messages" "textConnection" "w" "text" "opened" "no" "yes"
Can ...
can still be used in the function? sink
has further arguments that I may wish to use at some point.
EDIT
The file "data.txt"
can be created with the following code
> m <- matrix(c(13, 14, 4950, 20, 50, 4949, 22, 98, 4948, 30, 58, 4947, 43, 48, 4946),
5, byrow = TRUE)
> write.table(m, "data.txt", row.names = F, col.names = F)