Cross-format Tables in Bookdown

Note that if kableExtra 0.9.0 doesn't support the EPUB format. If you need to output tables in .epub, please upgrade to the dev version or version 1.0 on CRAN once it's released.

Use the "K-M" approach instead of "M-K"

Please read this chapter about the "K-M"/"M-K" approaches in bookdown: https://bookdown.org/yihui/bookdown/new-session.html

To generate cross-format tables with kableExtra in a multi-format bookdown project, you will have to use the "M-K" approach by setting new_session: true in _bookdown.yml. Somehow the "M-K" approach, which merges chapters to a big Rmd and then renders, shares the global environment across formats. For now, I'm not sure if this is a bug or intended behavior. It might be fixable in the future but please don't count on that. By setting new_session: true, we force R to use a new session for every chapter for different formats. In this way, tables are generated differently in different formats.

Note that the "M-K" approach is slower than the "K-M" approach. At the same time, packages and data are not shared accross chapter.

# Example _bookdown.yml
book_filename: "bookdown_example"
delete_merged_file: true
new_session: true
language:
  ui:
    chapter_name: "Chapter "

Prepare Your Tables for All Formats

In most cases, functions in kable and kableExtra use the same API to accomplish the same styling task in HTML and LaTeX. However, you also need some format specific settings so your tables will look good in both formats. Some common items here include the booktabs and longtable settings in kable and the bootstrap_options and latex_options in kable_styling.

Here is an example for a table that will work in HTML, LaTeX & EPUB.

library(kableExtra)
library(dplyr)
options(kableExtra.html.bsTable = T)
iris[1:10, ] %>%
  mutate_if(is.numeric, function(x) {
    cell_spec(x, bold = T, 
              color = spec_color(x, end = 0.9),
              font_size = spec_font_size(x))
  }) %>%
  mutate(Species = cell_spec(
    Species, color = "white", bold = T,
    background = spec_color(1:10, end = 0.9, 
                            option = "A", direction = -1)
  )) %>%
  kable(escape = F, align = "c", booktabs = T) %>%
  kable_styling(c("striped", "condensed"), 
                latex_options = "striped", 
                full_width = F)


haozhu233/kableExtra documentation built on April 13, 2024, 6:49 p.m.