MsGISRocker
MsGISRocker

Reputation: 642

Change bits of text specification / fontface (bold, italic,...) in a kableExtra table cell

I'm trying to format individual bits of text in a kableExtra table in rmakrdown, such as the example below:

---
output: pdf_document
---
```{r, echo=FALSE}
knitr::kable(data.frame(char = c('Hey *italics*','Hello **bold**', 'Hi ~~strikethrough~~~'),
             num = c(1,2,3)))
```

enter image description here

However, if I use kableExtra

```{r, echo=FALSE}
library(kableExtra)
knitr::kable(data.frame(char = c('Hey *italics*','Hello **bold**', 'Hi ~~strikethrough~~~'),
             num = c(1,2,3)))
```

I'll get:

enter image description here

I know there is cell_spec, row_spec and column_spec to format entire rows columns and cells, but that's not what I want.

I want to format only part of the text in a certain cell, but keep all functions from kableExtra for designing my table. There is also text_spec(), but I did not find any example on how to use it within a table.

P.S. I'm not that advanced and therefor would prefer working examples.

Upvotes: 2

Views: 2674

Answers (1)

user2554330
user2554330

Reputation: 44877

A fix for this is to tell kable() to produce a Markdown table:

---
output: pdf_document
---
```{r, echo=FALSE}
library(kableExtra)
knitr::kable(data.frame(char = c('Hey *italics*','Hello **bold**', 'Hi ~~strikethrough~~~'),
             num = c(1,2,3)), format="markdown")
```

format="pandoc" also works, but format="latex" (which I think would be the default here when kableExtra is involved) does not.

However, as pointed out in the comment, kableExtra doesn't support markdown, so you can't add all the nice features from that package. If you want that, the only solution is likely to use LaTeX markup instead of Markdown markup. That is, change the input to this:

---
output: pdf_document
header-includes:  \usepackage{soul}
---
```{r, echo=FALSE}
library(kableExtra)
knitr::kable(data.frame(char = c('Hey \\textit{italics}','Hello \\textbf{bold}', 
                                 'Hi \\st{strikethrough}'),
             num = c(1,2,3)), escape = FALSE)
```

You need escape = FALSE to tell kable not to display the LaTeX markup as text, but to leave it there for LaTeX to interpret.

Upvotes: 5

Related Questions