在RMarkdown代码输出中更改错误消息的颜色(HTML,PDF)

d.b*_*d.b 10 r knitr r-markdown

有没有办法在R Markdown中自动使错误的文本颜色变红,而无需稍后手动编辑HTML.

---
title: ""
---

#### Example 1

```{r e1, error = TRUE}
2 + "A"
```

#### Example 2

```{r e2, error = TRUE}
2 + 2
```
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,输出Example 1必须是红色.目前,我编辑生成的HTML(添加style="color:red;"到适当的标签),但我想知道是否有自动方式.假设在编织之前不知道代码是否会产生错误.

Mar*_*zer 11

1.使用针织钩

首选解决方案是使用输出挂钩进行错误:

```{r}
knitr::knit_hooks$set(error = function(x, options) {
  paste0("<pre style=\"color: red;\"><code>", x, "</code></pre>")
})
```
Run Code Online (Sandbox Code Playgroud)

输出挂钩通常允许我们控制R代码的不同部分的输出(整个块,源代码,错误,警告......).有关详细信息,请访问https://yihui.name/knitr/hooks/#output-hooks.

在此输入图像描述


2.使用JS/jQuery快速而肮脏的解决方案

这是我使用jQuery/Javascript的"快速而肮脏"的解决方案.只需将其添加到YAML标题下方即可.可能不是防弹,因为它使用字符串"Error"检查错误消息,该字符串也可能出现在其他应用程序中.

<script type="text/javascript">
$(document).ready(function() {
  var $chks = $("pre:not(.r) > code");
  $chks.each(function(key, val) {
    cntnt = $(this).html();
    if (cntnt.indexOf("Error") != -1) {
      $(this).css('color', 'red');
    }
  })
})
</script>
Run Code Online (Sandbox Code Playgroud)