嗨,我正在尝试在Rmarkdown .doc文档中使用flextable
来格式化表格。我喜欢flextable
提供的简单格式选项(但也接受其他类似的包),但发现某些基本功能并不总是可用。
我希望将表格适应Word文档的宽度,以便如果需要,文本将在列内换行以适应,但如果页面上有可用的空间,则会使列变宽,但不至于使列太宽以至于无法显示所有数据。
我制作了一个示例以展示我的问题。默认情况下,所有列都具有相同的宽度,并且文本被换行以适合,但因此浪费了空间。我想通过autofit
将列调整到数据大小,但这样会使列变得太宽而超出屏幕。我希望在mpg
,vs
和carb
更宽但仍然发生一些文本换行的中间状态。例如,我想要这个:
显然,我可以使用flextable::width
手动更改宽度,但我的表格是通过自动化过程生成的,因此我不知道每列应该有多宽。
以下是展示问题的示例,无论使用还是不使用autofit
都会出现问题。
---
title: "TestTable"
output: word_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
suppressWarnings(suppressPackageStartupMessages({library(knitr)
library(pander)
library(flextable)
library(tidyverse)
library(flextable)}))
```
## Normal Table
Without extra formatting, wraps text so that it fits on the page, but there is no need for column widths to be equal and could be wider on the page
```{r, echo=FALSE, results = 'asis' }
mydata <- mtcars %>% head(3) %>% select(mpg, cyl, hp,vs, gear, carb) %>%
mutate(mpg = paste0(mpg, "with extra stuff to make long"),
vs = paste0(vs, "+ extra stuff"),
carb = paste0(carb, "also with extra stuff to make longer"))
mytable <- mydata %>% flextable(theme_fun = theme_box)
mytable
```
## Table With autofit
But table with autofit goes off the edges of the page
```{r, echo=FALSE, results = 'asis' }
mytable %>% autofit()
```
## Table With autofit and manual breaks
And if manual breaks are inserted into the column autofit makes the columns too wide an they still go off the edges of the page
```{r, echo=FALSE, results = 'asis' }
mydataWithBreaks <- mtcars %>% head() %>% select(mpg, cyl, hp,vs, gear, carb) %>%
mutate(mpg = paste0(mpg, "\nwith extra stuff\n to make long"),
vs = paste0(vs, "+\n extra stuff"),
carb = paste0(carb, "\nalso with extra stuff\n to make longer"))
mydataWithBreaks %>% flextable(theme_fun = theme_box)%>% autofit()
```