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

查看:163
本文介绍了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天全站免登陆