RMarkdown kable 垂直对齐单元格 [英] RMarkdown kable vertically align cells

查看:27
本文介绍了RMarkdown kable 垂直对齐单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 Word):

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

I am struggling to sort the vertical centering (the space between "Number of Incident Occurences" on the top and bottom, so that the text is aligned in the middle of the row, left on the column.

注意,我创建的是 PDF 报告而不是 html.

Note, I am creating a PDF report and not 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(),但是当我这样做时,它会抱怨......有什么想法吗?

The vertical alignment seems to be pushing to the top. I came across "m", but that just middle aligns the columns. I'm wondering if I need to specify something special is row_spec() for all rows for align = "m", but when I do that, it complains.... Any ideas?

推荐答案

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

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.

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

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, "}")
  }

所以要重命名你运行的列:centerText("A short title")

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

这篇关于RMarkdown kable 垂直对齐单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆