Getting R printed texts to have color esp. in R markdown knits?

Viewed 6451

Very simple question: I love writing R notebooks/markdowns, and with something like highlight: tango I can give background color to codes when I knit my notebook to pdfs.

However, I don't know how to give colored backgrounds or colored fonts to printed outputs in R. For example, suppose I have the following chunk.

```{r, echo = FALSE}
writeLines("Help")
```

I'd like to see the word Help to be highlighted, say in red font with gray background. How can I achieve this?

Many thanks in advance.

3 Answers

with kableExtra, you can format your texts in R using text_spec

---
output: pdf_document
---

```{r}
library(kableExtra)
options(knitr.table.format = "latex")
```

`r text_spec("Help", color = "red")`

`r text_spec("Help Help", background = "#D05A6E", color = "white", bold = T)`

`r text_spec("Hello", font_size = 20)`

`r text_spec("World", angle = 180)`

You get enter image description here

Same goes for HTML enter image description here

See more in the Cell/Text Specification of the package vignette.

For PDF output, below are some latex commands to get colored text and shading. (For additional shading options, see this answer at the Tex Stack Exchange site.) However, I'm not sure how to get the output from writeLines shaded. Enclosing the code chunk in a \shaded environment causes an error. Hopefully someone will come along with a solution that works with code chunk output.

---
output: pdf_document
header-includes:
  - \usepackage{xcolor}
  - \usepackage{framed}
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```

\colorlet{shadecolor}{gray!10}

\color{red}

```{r}
writeLines("help")
```

\begin{shaded}

Red text with a gray background.

\end{shaded}

Red text.

\color{black}

Black text.

\colorlet{shadecolor}{red!10} 

\begin{shaded}

Black text with a red background.

\end{shaded}

\colorlet{shadecolor}{red!90} 

\begin{shaded}

Black text with a darker red background.

\end{shaded}

And here's the resulting PDF document:

enter image description here

For a way within R, my huxtable package lets you set background and text colour for tables. I don't know of any within-R package that does it for plain text (maybe crayon?)

library(huxtable)
ht <- hux(c("Red", "Blue"), c("White bg", "Black bg"))
text_color(ht)[, 1] <- c("red", "blue")
background_color(ht)[, 2] <- c("white", "black")
to_latex(ht) # or just print within a rmarkdown document
Related