我有一个函数fun
依赖于外部函数external
(即来自某个包)。我如何收集来自的所有警告external
在字符向量中?
这是一个最小的设置:
# 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)
}
然而,输出看起来像这样:
x <- fun()
# Warning message:
# In external() : warning from external...
print(x)
# character(0)
我不感兴趣suppressWarnings
,而是记录这些警告。当我使用sink
在函数之外它似乎可以工作,正如中所示这个答案 https://stackoverflow.com/a/27444424/5252007.
您可以使用tryCatch
为了这:
fun <- function() {
tryCatch(external(), warning = function(my_warn) my_warn$message)
}
x <-fun()
x
# [1] "warning from external..."
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)