我们的想法是尝试捕获警告并打印其消息。以下示例在 suppressWarnings 调用中,其效果应该与在 warning = FALSE 块中的效果相同。
这里我要运行的实际代码只是as.numeric(c("1", "A"))。我想打印代码生成的任何警告,尽管它位于 suppressWarnings 块内,并且我还想打印代码的结果:
suppressWarnings({
#--- Code chunk ----------------------------------------------------------#
withCallingHandlers(
expr = as.numeric(c("1", "A")),
warning = function(w) cat("** warning:", w$message, "**\n\n")
)
#--- End of code chunk ---------------------------------------------------#
})
#> ** warning: NAs introduced by coercion **
#>
#> [1] 1 NA
编辑
这是一个可重现的 Rmd,它显示了如何在计算结果打印后显示任何警告:
---
title: "test"
author: "Allan Cameron"
date: "27 November 2020"
output: html_document
---
```{r setup, include=FALSE, warning=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## Print warning after output
```{r test, warning=FALSE}
withCallingHandlers(
expr = as.numeric(c("1", "A")),
warning = function(w) warn <<- paste("** warning:", w$message, "**\n\n")
)
```
```{r print_warn, echo=FALSE}
if(exists("warn")) cat(warn)
```
这会产生: