Kim Kim - 11 months ago 141
LaTeX Question

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

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.

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download