RMarkdown kable vertically align cells

后端 未结 2 1128
暖寄归人
暖寄归人 2020-12-19 14:26

I am authoring a report using RMarkdown, and using kable and kableExtra to format and print the table. Here is what I want would look like the table to look like (made in Wo

相关标签:
2条回答
  • 2020-12-19 14:48

    This can be easily achieved in HTML by adding the extra_css argument. (for those who are searching for a similar solution in HTML and are only finding this post)

    column_spec(1,extra_css = "vertical- align:middle;")
    
    0 讨论(0)
  • 2020-12-19 15:03

    There doesn't seem to be a way to do this directly within kable and kableExtra. However, as when building a table to PDF through kable, it uses LaTeX to build the result. We can therefore integrate LaTeX functions directly into the table.

    This solution uses the multirow package. The cell to be centered vertically can be wrapped in \\multirow{1}{*}[0pt]{Cell content}, as follows:

    ---
    header-includes:
      - \usepackage{multirow}
    output: pdf_document
    ---
    
    ```{r}
    library(knitr)
    library(kableExtra)
    
    df <- data.frame(a = letters[1:5], b = 1:5)
    names(df) <- c("A very very very very very very very very very very very very very very very very very very long title",
                   "\\multirow{1}{*}[0pt]{A short title}")
    
    
    df %>% kable(format = 'latex', linesep = "", align = 'c', escape = F) %>% kable_styling(full_width = T)
    ```
    

    To make using this easier, you could make a function to do the renaming for you:

    centerText <- function(text){
        paste0("\\multirow{1}{*}[0pt]{", text, "}")
      }
    

    So to rename a column you run: centerText("A short title")

    0 讨论(0)
提交回复
热议问题