我在使用capture.output()
时遇到问题,我不知道为什么,因为它在很大程度上只是sink()
的包装器。
考虑这个使用sink()
:的琐碎示例
foo = function() warning("foo")
f = file()
sink(f, type = "message")
foo()
readLines(f)
## [1] "Warning message:" "In foo() : foo"
close(f)
这是意料之中的事。然而,capture.output()
不:
f = file()
capture.output(foo(), file = f, type = "message")
## Warning message:
## In foo() : foo
readLines(f)
## character(0)
close(f)
capture.output()
虽然对消息有效:
bar = function() message("bar")
f = file()
capture.output(bar(), file = f, type = "message")
readLines(f)
## [1] "bar"
close(f)
但根据文件,消息和警告都应该被捕获:
发送到stderr()
的消息(包括来自message
、warning
和stop
的消息(由type = "message"
捕获。
这里缺少什么
@MrFlick的注释指向一个潜在的解决方案,前提是您可以控制传递给warning()
的参数。如果使用参数immediate. = TRUE
,则capture.output()
可以检索警告消息。
baz = function() warning("baz", immediate. = TRUE)
res = capture.output(baz(), type = "message")
print(res)
## [1] "Warning in baz() : baz"
编辑
或者,@user2554330指出,您可以使用options(warn = 1)
在全局范围内立即打印警告。
oldopt = getOption("warn")
options(warn = 1)
res = capture.output(foo(), type = "message")
print(res)
## [1] "Warning in foo() : foo"
options(warn = oldopt)
编辑2
为了完整起见,我认为使用withCallingHandlers
指出这种替代方法是有帮助的,它不需要对选项进行任何更改,并且可能是一种更干净的解决方案,具体取决于应用程序。考虑以下嵌套警告示例:
foo = function() {
warning("foo")
bar()
}
bar = function() {
warning("bar")
baz()
}
baz = function() {
warning("baz")
TRUE
}
# create a container to hold warning messages
logs = vector("character")
# function to capture warning messages
log_fun = function(w) logs <<- append(logs, w$message)
# function call with message capturing
withCallingHandlers(foo(), warning = log_fun)
## [1] TRUE
## Warning messages:
## 1: In foo() : foo
## 2: In bar() : bar
## 3: In baz() : baz
print(logs)
## [1] "foo" "bar" "baz"
请注意,withCallingHandlers
允许您为不同的信号条件指定不同的行为,例如warnings
和messages
可以存储在单独的变量中。