How to Change Fontface (Bold/Italics) for a Cell in a Kable Table in Rmarkdown

How to change fontface (bold/italics) for a cell in a kable table in rmarkdown?

Highlighting cells, rows or columns with pander is pretty straightforward:

> df <- data.frame(c('a','b','c'),c(1,2,3))
> emphasize.strong.cells(which(df == 3, arr.ind = TRUE))
> pander(df)

-------------------------------
c..a....b....c.. c.1..2..3.
------------------ ------------
a 1

b 2

c **3**
-------------------------------

But adding horizontal line to the table is out of the scope of markdown table specifications.

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

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.

Bold a column in knitr::kable(df)

You can use CSS to do it, as described here: Using CSS how to change only the 2nd column of a table.

You can just put the CSS directly into the text, outside of the code chunk, or in a separate file mentioned in the YAML header. For example,

<style>
table td:nth-child(2){
font-weight: bold;
}
</style>

```{r}
employee <- c('John Doe','Peter Gynn','Jolie Hope')
salary <- c(21000, 23400, 26800)
startdate <- as.Date(c('2010-11-1','2008-3-25','2007-3-14'))

employ.data <- data.frame(employee, salary, startdate)

knitr::kable(employ.data)
```

This will change every table in the document; you may want a more specific selector.

I don't know a simple way to add a class to a particular table using kable() in R Markdown, but this kludge will do it. In the CSS, use

<style>
table.salarytable td:nth-child(2){
font-weight: bold;
}
</style>

to restrict the change to class salarytable, then in the code chunk use

knitr::kable(employ.data, "html", 
table.attr = 'class="table table-condensed salarytable"'

to tell knitr to output HTML and give the table the usual class for an R Markdown table, as well as your own salarytable class.

Kable caption in rmarkdown file in HTML in bold

Does this markdown-oriented solution work for you?

```{r, results='asis'}
kable(head(iris), caption = '**I want this in Bold**') %>%
kableExtra::kable_styling(bootstrap_options = c("striped", "hover", "condensed","responsive"))
```

for html-output this should work:

```{r, results='asis'}
kable(head(iris), caption = '<b>I want this in Bold</b>', format = 'html') %>%
kableExtra::kable_styling(bootstrap_options = c("striped", "hover", "condensed","responsive"))
```

for pdf-output this should work:

```{r, results='asis'}
kable(head(iris), caption = '\\textbf{I want this in Bold}', format = 'latex') %>%
kableExtra::kable_styling(bootstrap_options = c("striped", "hover", "condensed","responsive"))
```

Bold formatting for significant values in a Rmarkdown table

We could do it like this, using pander:

library(pander)
library(Hmisc)

# compute matrix correlation
df3 <- rcorr(as.matrix(mtcars), type="pearson")

# we get a list of three items, first item is df of r values
# third item in df of p values
df3

# make cells of r values bold if p value is <0.01
emphasize.strong.cells(which(df3[[3]] < 0.001, arr.ind = TRUE))
pander(df3[[1]])

Which gives:

----------------------------------------------------------
  mpg cyl disp hp
---------- ----------- ----------- ----------- -----------
**mpg** 1 **-0.8522** **-0.8476** **-0.7762**

**cyl** **-0.8522** 1 **0.902** **0.8324**

**disp** **-0.8476** **0.902** 1 **0.7909**

**hp** **-0.7762** **0.8324** **0.7909** 1

**drat** **0.6812** **-0.6999** **-0.7102** -0.4488

**wt** **-0.8677** **0.7825** **0.888** **0.6587**

**qsec** 0.4187 **-0.5912** -0.4337 **-0.7082**

**vs** **0.664** **-0.8108** **-0.7104** **-0.7231**

**am** **0.5998** -0.5226 **-0.5912** -0.2432

**gear** 0.4803 -0.4927 **-0.5556** -0.1257

**carb** -0.5509 0.527 0.395 **0.7498**
----------------------------------------------------------
[output snipped]

And when rendered into HTML looks like (side-effect of making the row names bold also):

Sample Image

Is something like this possible using only knitr?

kableExtra: adjust font face and background of add_header_above()

While providing an answer for this related post on SO on changing font size in kableExtra tables for manually added header/grouping rows added with add_header_above(), I came across the solution to my own question.

add_header_above() actually provides many, many arguments to twist the output as desired:

add_header_above(kable_input, header = NULL, bold = FALSE,
italic = FALSE, monospace = FALSE, underline = FALSE,
strikeout = FALSE, align = "c", color = NULL, background = NULL,
font_size = NULL, angle = NULL, escape = TRUE, line = TRUE,
line_sep = 3, extra_css = NULL, include_empty = FALSE)

An illustrative MWE:

vec <- c("Properties A", "Properties B")
mtcars[1:3,1:4] %>% kable() %>%
kable_styling() %>%
# 2nd. level of grouping rows added on top of the table
add_header_above(
c(" " = 1,
"Features" = 2,
"Features" = 2),
font_size = 15, italic = TRUE) %>%
# 1st. level of grouping rows added on top of the table (with dynamic labels as requested)
add_header_above(
c(" " = 1,
setNames(2, vec[1]),
setNames(2, vec[1])),
font_size = 25, bold = TRUE, color = "orange", background = "lightblue") %>%
# adjust font face and background
row_spec(row = 0, italic = T) %>%
row_spec(row = 0, background = "orange")

Sample Image

Selecting and colouring single table cells with kableExtra in R markdown cell_spec

As you have seen, the cell_spec function is useful if you want to colour a whole row or column. As kableExtra does not supply a function to directly edit a single cell, the "easiest" way to do this is to directly paste the LaTeX commands into the cell. I have used this approach in a similar answer here:

---
output: pdf_document
header-includes:
- \usepackage{booktabs}
---

```{r pressure, echo=FALSE}

df <- mtcars[1:10, 1:5]

df[1,5] <- paste0("\\underline{", df[1,5], "}")
df[1,1] <- paste0("\\textcolor{red}{", df[1,1], "}")
df[2,2] <- paste0("\\textcolor{green}{\\textbf{", df[2,2], "}}")
# # Equivalent to:
# library(kableExtra)
# df[1, 5] <- cell_spec(df[1, 5], "latex", underline = T)
# df[1, 1] <- cell_spec(df[1, 1], "latex", color = "red")
# df[2, 2] <- cell_spec(df[2, 2], "latex", color = "green", bold = T)

knitr::kable(df, format="latex", booktabs = T, escape = F)

```

Sample Image

You can adapt this to work for your example. You may want to check out the available LaTeX formatting here: https://www.sharelatex.com/learn/Bold,_italics_and_underlining

How do I maintain the formatting of text in a cell in an Excel spreadsheet when importing into R markdown?

In answer to your question, you cannot maintain the formattting, but you can replicate it.

When the read_xlsx() function is run, it extracts the data from the cells but does not retain any of the formatting. As a result, any bold font will not be automatically transferred to R.

The easiest way of achieving what you want would be to add the bold text after you have loaded the data into R. The kableExtra is perfect for doing such things. Here is an example, using the column_spec and row_spec functions to change the format of the cells:

```{r}
library(kableExtra)

knitr::kable(iris[1:5,], format = "latex", booktab = TRUE) %>%
column_spec(1, bold = T) %>%
row_spec(0, bold = T, color = "red")

```

Sample Image

You can customise a number of properties (run ?row_specto load the helper):

  • Font size
  • Alignment
  • Text Angle
  • Text Colour
  • Background Colour

If you need more fine tuning of cell formatting to specific cells, you can investigate the cell_spec function.

View the full guidance for customising LaTeX tables here: https://haozhu233.github.io/kableExtra/awesome_table_in_pdf.pdf



Related Topics



Leave a reply



Submit