Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 949
Kim Avatar asked Nov 15 '17 01:11

Kim


People also ask

How do I color 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 you show output in R markdown in knitting?

Rendering Output There are two ways to render an R Markdown document into its final output format. If you are using RStudio, then the “Knit” button (Ctrl+Shift+K) will render the document and display a preview of it.

How do I add color in Markdown?

Markdown doesn't support color but you can inline HTML inside Markdown, e.g.: <span style="color:blue">some *blue* text</span>. As the original/official syntax rules state (emphasis added): Markdown's syntax is intended for one purpose: to be used as a format for writing for the web.


1 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.

like image 99
Hao Avatar answered Sep 19 '22 23:09

Hao