RMarkdown kable 垂直对齐单元格

RMarkdown kable vertically align cells

我正在使用 RMarkdown 编写报告,并使用 kable 和 kableExtra 来格式化和打印 table。这是我想要的 table 看起来像(用 Word 制作):

我正在努力对顶部和底部的 "Number of Incident Occurences" 之间的垂直居中进行排序(space,以便文本在行的中间对齐,在列的左侧对齐。

请注意,我正在创建 PDF 报告,而不是 html。

这是一个最小的例子:

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",
               "A short title")

df %>% kable(format = 'latex', linesep = "", align = 'c', escape = F) %>% kable_styling(full_width = T)

这是输出的样子:

垂直对齐方式似乎在推到顶部。我遇到了 "m",但那只是中间对齐列。我想知道我是否需要为 align = "m" 的所有行指定一些特殊的东西 row_spec(),但是当我这样做时,它会抱怨....有什么想法吗?

似乎没有办法直接在 kable 和 kableExtra 中执行此操作。然而,当通过 kable 将 table 构建为 PDF 时,它使用 LaTeX 来构建结果。因此,我们可以将 LaTeX 函数直接集成到 table.

此解决方案使用 multirow 包。要垂直居中的单元格可以用\multirow{1}{*}[0pt]{Cell content}包裹起来,如下:

---
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)
```

为了更容易使用它,您可以创建一个函数来为您重命名:

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

因此,要重命名您 运行 的列:centerText("A short title")

这可以在 HTML 中通过添加 extra_css 参数轻松实现。 (对于那些在 HTML 中搜索类似解决方案并且只找到这个 post 的人)

column_spec(1,extra_css = "vertical- align:middle;")

August 2020 开始,kableExtra 包中的 column_spec() 函数有一个 latex_valign 参数。这仅在您还指定列宽时才有效,因此它与 kable_styling(full_width = T)

不兼容
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",
               "A short title")

df %>% 
  kable(format = 'latex', 
        linesep = "", 
        align = 'c') %>% 
  column_spec(1:2,
              width = "3in",
              latex_valign = "m")