RMarkdown: How to change the font color?

In RMarkdown is there a way to specify the font color?

There doesn't seem to be an option while browsing through the chunk options


Solution 1:

The answer given at the link provided by @Ben Bolker:

Roses are <span style="color:red">red</span>, 
violets are <span style="color:blue">blue</span>.

does work if you select HTML (ioslides) as the output format.

However, it does not work if you select pdf (beamer) as output format. If you want to create a pdf, use LaTeX syntax:

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

Solution 2:

I create a function like this:

## Color Format
colFmt <- function(x,color) {
  
  outputFormat <- knitr::opts_knit$get("rmarkdown.pandoc.to")
  
  if(outputFormat == 'latex') {
    ret <- paste("\\textcolor{",color,"}{",x,"}",sep="")
  } else if(outputFormat == 'html') {
    ret <- paste("<font color='",color,"'>",x,"</font>",sep="")
  } else {
    ret <- x
  }

  return(ret)
}

Then you can use it inline like this:`r colFmt("MY RED TEXT",'red')`, and colored text will be rendered regardless of whether working on latex or HTML document.

Solution 3:

This seems to work very well in both output formats, pdf and html:

Roses are $\color{red}{\text{beautiful red}}$, 
violets are $\color{blue}{\text{lovely blue}}$.

Hope it helps.

Solution 4:

An output-format agnostic solution would be to use the dedicated text_spec() function in the kableExtra package:

Roses are `r kableExtra::text_spec("red", color = "red")`,

violets are `r kableExtra::text_spec("blue", color = "blue")`

Solution 5:

Others have provided answers for output other than Word. For Word, you can use the Pandoc custom-style syntax to accomplish this with the aid of a reference word document. First, inside your reference.docx template, create a new Word style with a short, distinct name. If you want your font color to apply to a full paragraph, you can use the default, “Linked Paragraph and Character” style type. If you only want to emphasize some words in a paragraph with color, you need to select the “Character” style type. Change the font color (and any other styling you need) and save the reference.docx file.

Then, inside your .Rmd file, you can use the tag as follows:

<div custom-style=“DivCol”>Whole paragraph of colored text</div>

Just a <span custom-style=“SpanCol”>few words</span> of colored text

A word regarding style names - for reasons I don’t understand, this process did not work with the style name “Span_Add” but “SpanAdd” was fine.