4.1 Font color

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{}{}. This requires the extra LaTeX package xcolor.

As an example of changing the color in PDF text:

    extra_dependencies: ["xcolor"]

Roses are \textcolor{red}{red}, violets are \textcolor{blue}{blue}.

If you want to design an R Markdown document for multiple output formats, you should not embed raw HTML or LaTeX code in your document, because they will be ignored in the other output formats (e.g., LaTeX code will be ignored in HTML output). We can write a custom function to insert the correct syntax depending on the output format using the is_latex_output() and is_html_output() functions in knitr as follows:

colorize <- function(x, color) {
  if (knitr::is_latex_output()) {
    sprintf("\\textcolor{%s}{%s}", color, x)
  } else if (knitr::is_html_output()) {
    sprintf("<span style='color: %s;'>%s</span>", color, 
  } else x

We can then use the code in an inline R expression `r colorize("some words in red", "red")`, which will create some words in red (you may not see the red color if you are reading this book printed in black and white).