Search code examples
rlatexr-markdownkableextra

R kableExtra two center alignments: one for columns with linebreaks and another for others


Output Desired

Using R kableExtra, I want to create the following table formatting in both PDF and HTML output (at least the newline, centering and LaTeX equations are present) like the following. enter image description here

The Code Attempt

The following R code renders the desired PDF output correctly:

#-------------------
library(tidyverse)
library(kableExtra)
#-------------------

fs_dt <- tibble(
  school = 1:4,
  nstudents = c(1471,890,1021,1587),
  nf_total = c(792,447,511,800),
  nf_intv = c(25,15,20,40),
  nsmokers = c(10,3,6,27)
)

fs_dt %>% 
 kbl(booktabs = T,
    col.names = linebreak(c("School",
                  "No. of students",
                  "No. of females\n($M_i$)",
                  "No. of females interviewed\n($m_i$)",
                  "$\\sum_{i\\in\\mathcal{S}} y_{ij}$"),
                  align = "c"),
    escape = FALSE,
    align = "ccccc"
    ) %>% 
  kable_styling(latex_options = c("striped","hold_position"))

However, the HTML output looks like the following where the third and fourth column names are missing.

enter image description here

The Question

How can we achieve both output using a single code without resorting to conditional coding (e.g., is_html_output()/is_latex_output())?


Solution

  • Here is a little problem.

    Library kableExtra doesn't work with \n in "HTML-mode".

    What do you can to do?

    1. You can change \n to <br> when knitting to HTML.

    2. It isn't conveniently, especially, when you have a lot of tables (changing \n to <br> every time.

      For this case you can use column_spec:

      #your code above
      escape = FALSE,
      align = "ccccc"
      ) %>% 
      column_spec(3, width = "3cm") %>%
      column_spec(4, width = "5.3cm") %>% #4.8 cm for PDF!!!
      kable_styling(latex_options = c("striped","hold_position"))
      

      You should determinate your width every time (sometimes for the every output), it is a little tedious.

      Every solution have some underwater rocks, so we must fight with compromises :(

    enter image description here