如何控制 knitr 中的 R 警告到 rmarkdown
How to control R warnings in knitr to rmarkdown
我有一个带有循环的块,可以生成线性模型的图像和结果。有时模型会产生不收敛警告。如果我让 warning=TRUE
作为块条件,图像和结果将变得完全混乱。但我想打印警告,所以我尝试通过
cat(names(last.warning))
(感谢 this SO)。然后我在 knitr
:
时收到下一个错误
Error in eval(expr, envir, enclos) : object 'last.warning' not found
Calls: <Anonymous> ... handle -> withCallingHandlers -> withVisible -> eval -> eval
Execution halted
我能做什么?
谢谢!
想法是尝试捕获警告并打印其消息。下面的示例在 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)
```
这会产生:
我有一个带有循环的块,可以生成线性模型的图像和结果。有时模型会产生不收敛警告。如果我让 warning=TRUE
作为块条件,图像和结果将变得完全混乱。但我想打印警告,所以我尝试通过
cat(names(last.warning))
(感谢 this SO)。然后我在 knitr
:
Error in eval(expr, envir, enclos) : object 'last.warning' not found
Calls: <Anonymous> ... handle -> withCallingHandlers -> withVisible -> eval -> eval
Execution halted
我能做什么?
谢谢!
想法是尝试捕获警告并打印其消息。下面的示例在 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)
```
这会产生: