在 rmarkdown pdf 输出中包装比例表列名的有效方法

Efficient way to wrap column names of proportion tables in rmarkdown pdf output

提问人:John J. 提问时间:1/13/2018 最后编辑:John J. 更新时间:1/15/2018 访问量:6530

问:

我正在使用 questionr 包制作行比例的加权表。当列名太长时,我想换行它们。因为我要制作数百个表,所以该解决方案需要处理具有不同列数的表。我还想避免将所有列设置为特定宽度。理想情况下,短列名称将保持其正常宽度,而超过指定最大长度的名称将被换行。

以下是我迄今为止尝试过的一堆解决方案,写成 .Rmd 文件:

---
title: "Example"
output: pdf_document
---

```{r setup, include=FALSE}
library(questionr)
library(knitr)
data("happy")
```


A simple weighted table with the "kable" method:
```{r table1, echo=TRUE}
kable(wtd.table(happy$degree, happy$happy, weights = happy$wtssall),
  digits = 0)
```

The same "kable" table, but with row proportions:
```{r table2, echo=TRUE}
kable(rprop(wtd.table(happy$degree, happy$happy, weights = happy$wtssall)),
  digits = 0)
```

I want to wrap the column headers, but kableExtra::column_spec() gives an error.
Even if it worked it requires manually setting each column width.:
```{r table3, echo=TRUE}
library(kableExtra)
kable(rprop(wtd.table(happy$degree, happy$happy, weights = happy$wtssall)),
  digits = 0) %>%
  column_spec(column = 2, width = ".25in")
```

Maybe str_wrap will do the trick?
```{r table4, echo=TRUE}
library(stringr)
kable(rprop(wtd.table(happy$degree, str_wrap(happy$happy, width = 8),
                  weights = happy$wtssall)),
  digits = 0)
```

Giving up on knitr::kable(), maybe pander has a solution.
Here is the simple weighted frequency table.
```{r table5, echo=TRUE, results='asis'}
library(pander)
pandoc.table(wtd.table(happy$degree, str_wrap(happy$happy, width = 8),
                  weights = happy$wtssall),
         split.cells=8)
```

So far, so good. But it doesn't work for the table of row proportions,
because the rprop table is of class ([1]"proptab" [2]"table")
while the wtd.table() is just class "table"
```{r table6, echo=TRUE, results='asis', error=TRUE}
pandoc.table(rprop(wtd.table(happy$degree, str_wrap(happy$happy, width = 8),
                  weights = happy$wtssall)),
         split.cells=8)
```

But wait! I can pass a kable() product as pandoc output.
This table looks great, but I don't think I pass any
pandoc.table() arguments like "split.cells=8" to it.
```{r table7, echo=TRUE, results='asis', error=TRUE}
kable(rprop(wtd.table(happy$degree, happy$happy, weights = happy$wtssall)),
  digits = 0, format = "pandoc")
```

这是它的输出.Rmd 文件如下所示:enter image description here

enter image description here

R R-Markdown 潘多克 kableextra kable

评论


答:

7赞 Hao 1/15/2018 #1

至少,对于 ,您需要在函数中将格式指定为 或 。kableExtrakablelatexhtmlenter image description here

要使其动态化,您可以在表进入 kable 之前将其保存到变量中,并在函数中使用 2:(ncol(your_table) + 1)(column_name列为 +1)。column_spec

评论

1赞 John J. 1/17/2018
谢谢,这接近我想要的。突出的问题是,该解决方案使所有色谱柱的宽度为 0.5 英寸。在我的问题中,我正在尝试设置最大列宽。我想避免拉伸较短的列。
0赞 John J. 1/17/2018
此外,这里有一个使表长度动态的单行解决方案:column = 2:(length(unique(happy$happy[!is.na(happy$happy)])))