Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change color of error messages in RMarkdown code output (HTML, PDF)

Is there a way to automatically make text color of errors red in R Markdown without manually editing the HTML later.

---
title: ""
---

#### Example 1

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

#### Example 2

```{r e2, error = TRUE}
2 + 2
```

In the above code, output of Example 1 would have to be red. Currently, I edit the generated HTML (add style="color:red;" to the appropriate tag) but I am wondering if there is an automatic way. Assume that it is not known before knitting whether the code will generate error.

like image 626
d.b Avatar asked Nov 16 '17 23:11

d.b


People also ask

How do you change the color of text in R Markdown?

The Markdown syntax has no built-in method for changing text colors. We can use HTML and LaTeX syntax to change the formatting of words: For HTML, we can wrap the text in the <span> tag and set color with CSS, e.g., <span style="color: red;">text</span> . For PDF, we can use the LaTeX command \textcolor{}{} .

How do I change R Markdown from HTML to PDF?

To transform your markdown file into an HTML, PDF, or Word document, click the “Knit” icon that appears above your file in the scripts editor. A drop down menu will let you select the type of output that you want. When you click the button, rmarkdown will duplicate your text in the new file format.


1 Answers

1. Use a knitr hook

The preferred solution is to use the output hook for errors:

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

Output hooks in general allow us to control the output of different parts of our R code (the whole chunk, the source code, errors, warnings, ...). For details check https://yihui.name/knitr/hooks/#output-hooks.

enter image description here


2. Quick and dirty solution using JS/jQuery

And this is my "quick and dirty" solution using jQuery/Javascript. Just add it beneath the YAML header. Might not be bulletproof, since it checks for error messages using the string "Error" which might occur in other applications as well.

<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>
like image 92
Martin Schmelzer Avatar answered Oct 21 '22 02:10

Martin Schmelzer