【发布时间】:2019-08-26 12:25:41
【问题描述】:
我有一个函数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)
我对@987654328@ 不感兴趣,而是记录这些警告。当我在函数之外使用sink 时,它似乎可以工作,正如this answer 中所示。
【问题讨论】:
-
你知道
warnings已经登录了吗? -
你的意思是在R创建的
last.warning中? -
是的,但您可能还想查看选项
warning.expression以覆盖警告行为 - 即记录而不是打印。 -
@James,你能扩展一点吗?我觉得这个方法很有意思!
-
不幸的是,这可能是不可能的,这里有一个讨论:stackoverflow.com/questions/48071718/…