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

Is there a way to format a single cell in a table in rmarkdown? I use kable to create a table as follows:

library(knitr) kable(data.frame(c('a','b','c'),c(1,2,3))) 

I want to highlight "c" in the last row, and also add a horizontal line at the end of the table. Any pointers?

+8
r markdown knitr r-markdown
source share
2 answers

The selection of cells, rows or columns with pander 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 a horizontal row to the table goes beyond the specification of the markup table .

+3
source share

Just summarizing the question of including other fonts. Pandoc offers other ways to easily reformat the text and, as explained in the Cheatsheet RMarkdown :

  • italics can be achieved using *italics*
  • bold can be achieved using **bold**
  • strikethrough can be achieved using ~~strikethrough~~

This output will support various output methods, including PDF , html and word :

Here is an example:

 --- output: pdf_document: default --- '''{r} knitr::kable(data.frame(char = c('*a*','**b**','~~c~~'), num = c(1,2,3))) ''' 

enter image description here

Apply formatting with the function

To simplify the selection of cells for reformatting, I have compiled the following format_cells functions.

 format_cells <- function(df, rows ,cols, value = c("italics", "bold", "strikethrough")){ # select the correct markup map <- setNames(c("*", "*", "~~"), c("italics", "bold", "strikethrough")) markup <- map[value] for (r in rows){ for(c in cols){ # Make sure values are not factors df[[c]] <- as.character( df[[c]]) # Update formatting df[r, c] <- paste0(markup, df[r, c], markup) } } return(df) } 

It allows the user to select the row and columns of cells that need to be reformatted and select the style to apply. You can select multiple cells at the same time if you need to reformat multiple values ​​in a row / column. Here is an example:

 library(tidyverse) df <- data.frame(char = c('a','b','c'), num = c(1,2,3)) df %>% format_cells(1, 1, "italics") %>% format_cells(2, 2, "bold") %>% format_cells(3, 1:2, "strikethrough") %>% knitr::kable() 

Further reading: The kableExtra package was written to offer many additional table style controls. However, the recommendations are different for different types of output, so there are different approaches to HTML and LaTeX

+3
source share

All Articles