I have a function fun
that relies on an external function external
(i.e., from some package). How can I collect all the warnings that come out of external
in a character vector?
This is a minimal setup:
# External function from another package.
external <- function() {
warning("warning from external...")
}
# Function meant to capture the warnings.
fun <- function() {
# Create variable to store the warnings.
warns <- vector("character")
# Create connection for the sink.
connection <- textConnection("warns", "wr", local = TRUE)
# Start collecting.
sink(connection, type = "message")
# Call external function and produce a warning.
external()
# Reset the sink.
sink(type = "message")
# Close the connection.
close(connection)
return(warns)
}
The output, however looks like this:
x <- fun()
# Warning message:
# In external() : warning from external...
print(x)
# character(0)
I am not interested in suppressWarnings
, but rather to log these warnings. When I use sink
outside of a function it seems to work, just as indicated in this answer.