【问题标题】:Knit HTML fails to output upon code error代码错误时Knit HTML无法输出
【发布时间】:2016-04-26 02:49:48
【问题描述】:

我的 R 脚本创建了一系列矩阵和这些矩阵的箱线图。其中一个矩阵可能为空。对空矩阵执行 boxplot 会出错。那不是问题。问题是,在 R Markdown 中运行此代码以编织 HTML 文件时,此错误会停止执行并导致没有 HTML 文件。

作为一个补丁,我认为只有在矩阵不是全部 NA 时才运行 boxplot。这样可行。然而我想知道我是否可以让 knitr 简单地忽略这个错误,而不是修补我的代码。谢谢。

这是错误信息:

Error in plot.window(xlim = xlim, ylim = ylim, log = log, yaxs = pars$yaxs) : 
  need finite 'ylim' values
Calls: <Anonymous> ... boxplot -> boxplot.default -> do.call -> bxp -> plot.window
In addition: Warning messages:
1: In min(x) : no non-missing arguments to min; returning Inf
2: In max(x) : no non-missing arguments to max; returning -Inf
Execution halted

可重现的代码:

```{r,echo = FALSE, warning = FALSE, message=FALSE}
knitr::opts_chunk$set(cache=TRUE)

#MatrixPos - not empty
MatrixPos <- structure(list(difFwd1 = 0, difFwd2 = 0.200000000000045, difFwd3 = 0.100000000000136,difFwd4 = 0, difFwd5 = 0.200000000000045), .Names = c("difFwd1","difFwd2", "difFwd3", "difFwd4", "difFwd5"), row.names = "155", class = "data.frame") 

#MatrixNeg - empty
MatrixNeg <- structure(list(difFwd1 = NA_real_, difFwd2 = NA_real_, difFwd3 = NA_real_,difFwd4 = NA_real_, difFwd5 = NA_real_), .Names = c("difFwd1","difFwd2", "difFwd3", "difFwd4", "difFwd5"), row.names = "NA", class = "data.frame") 

boxplot(MatrixPos, notch = TRUE, outline = TRUE)
boxplot(MatrixNeg, notch = TRUE, outline = TRUE)

```
###note must remove the four spaces for the code to work in R-Studio


#Solution attempt:
if(!all(is.na(MatrixNeg))) boxplot(MatrixNeg, notch = TRUE, outline = TRUE)

【问题讨论】:

    标签: r knitr r-markdown boxplot


    【解决方案1】:

    尝试在你的区块选项中设置error=TRUE

    ```{r,echo = FALSE, warning = FALSE, message=FALSE, error=TRUE}
    knitr::opts_chunk$set(cache=TRUE)
    
    #MatrixPos - not empty
    MatrixPos <- structure(list(difFwd1 = 0, difFwd2 = 0.200000000000045, difFwd3 = 0.100000000000136,difFwd4 = 0, difFwd5 = 0.200000000000045), .Names = c("difFwd1","difFwd2", "difFwd3", "difFwd4", "difFwd5"), row.names = "155", class = "data.frame") 
    
    #MatrixNeg - empty
    MatrixNeg <- structure(list(difFwd1 = NA_real_, difFwd2 = NA_real_, difFwd3 = NA_real_,difFwd4 = NA_real_, difFwd5 = NA_real_), .Names = c("difFwd1","difFwd2", "difFwd3", "difFwd4", "difFwd5"), row.names = "NA", class = "data.frame") 
    
    boxplot(MatrixPos, notch = TRUE, outline = TRUE)
    boxplot(MatrixNeg, notch = TRUE, outline = TRUE)
    
    ```
    

    给出这个结果:

    来自knitr options: "error: (TRUE;logical) 是否保留错误(来自stop());默认情况下,即使出现错误,评估也不会停止!!如果我​​们想让R停止错误,我们需要将此选项设置为 FALSE"

    【讨论】:

    • 我知道必须有一个简单的答案。就是找不到。谢谢vm。
    • 我认为您也可以将cache 添加到块选项中:{r, cache = TRUE, echo = FALSE, warning = FALSE, message = FALSE, error = TRUE}
    • @Pgibas 没错,我只是不确定他是否还有其他原因遗漏了它(还没有看到他的其余代码)
    猜你喜欢
    • 2016-07-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-19
    • 2021-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-29
    相关资源
    最近更新 更多