Search code examples
rr-markdownkableextra

How to align table footnotes with kableExtra?


I tried to use kableExtra::add_footnote() to create footnotes for my PDF output. I want to make the footnotes align in both sides, reduce the font size and the line space. I did try to add threeparttable = T in my code, but it didn't work.

library(magrittr)
data("mtcars")
tbl <- tibble::tibble(mpg = mean(mtcars$mpg), cyl = mean(mtcars$cyl), disp = mean(mtcars$disp)) %>% as.data.frame()

rownames(tbl) <- c("Mean")
knitr::kable(tbl, "latex",
             booktabs = T,
             digits = 2, 
             escape = FALSE) %>% 
  kableExtra::add_header_above(c("Mean" = 4)) %>% 
  kableExtra::kable_styling(latex_options = "hold_position", full_width = T,  font_size = 10) %>% 
  kableExtra::column_spec(1, width = "3cm") %>% 
  kableExtra::add_footnote("I want to add some long long long long long footnotes here, and I want the format looks elegant enough.")

enter image description here


Solution

  • I think full_width = T in kable_styling is the option that causes the issue. Without that it seems to work for me.

    ---
    output: pdf_document
    header-includes: 
      - \usepackage{caption} 
      - \usepackage{booktabs} 
      - \usepackage{longtable}
      - \usepackage{threeparttablex} 
    ---
    
    ```{r, echo=FALSE}
    library(magrittr)
    data("mtcars")
    tbl <- data.frame(mpg = mean(mtcars$mpg), cyl = mean(mtcars$cyl), disp = mean(mtcars$disp))
    
    rownames(tbl) <- c("Mean")
    knitr::kable(tbl, "latex",
                 booktabs = T,
                 digits = 2, 
                 escape = FALSE) %>% 
      kableExtra::add_header_above(c("Mean" = 4)) %>% 
      kableExtra::kable_styling(latex_options = "hold_position", font_size = 10) %>% 
      kableExtra::column_spec(c(1:4), width = "3cm") %>%
      kableExtra::add_footnote(
        "I want to add some long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long footnotes here.",
        threeparttable = T
      )
    ```
    

    rendered result