flextable 在 Rmarkdown 中自动适应 word 文档导致 table 超出页边距

flextable autofit in a Rmarkdown to word doc causes table to go outside page margins

您好,我正在尝试在 Rmarkdown .doc 文档中使用 flextable 来格式化我的 table。我喜欢 flextable 提供的简单格式选项(但对其他类似包开放),但发现一些我认为应该是基本功能的功能并不总是有效。

我想让 table 适合 word 文档的宽度,这样如果需要,文本将在一列中换行以适合,但如果页面列上有可用的 space将变得更宽,但不会达到列宽到无法显示所有数据的程度。

我在下面做了一个例子来说明我的问题。默认情况下,所有列的宽度都相同,并且文本被换行以适合,但因此 space 被浪费了。我想使列适合数据(使用 autofit),但这会使列太宽以至于超出屏幕范围。我希望有一个 mpgvscarb 更宽的快乐媒介,但一些文本换行仍在发生。例如。我想要这个:

显然我可以使用 flextable::width 手动更改宽度,但我的 table 是通过自动化过程生成的,所以我不知道我希望每列的宽度。

这是我的示例,它显示了 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()



```

我已经编写了一个函数来使 table 适合目前运行良好的页面,尽管我仍然有点惊讶没有内置函数来执行此操作(例如) 知道页面本身的宽度,所以如果有人知道任何仍然热衷于听到。

FitFlextableToPage <- function(ft, pgwidth = 6){

  ft_out <- ft %>% autofit()

  ft_out <- width(ft_out, width = dim(ft_out)$widths*pgwidth /(flextable_dim(ft_out)$widths))
  return(ft_out)
}

仅供参考 - 我今天 运行 遇到了同样的问题并使用了您的代码(谢谢)。但它仍然困扰着我,因为我不能完全正确。我在 Officedown 软件包网站(同一作者;https://github.com/davidgohel/officedown)上注意到他们使用了 set_table_properties(layout = "autofit"),所以我试了一下。无论出于何种原因,它在这样做时都按预期工作!我还使用了默认设置的 officedown,所以也许两者可以很好地协同工作。

我在使用 autofit() 函数时遇到了类似的问题。 当我将函数 fit_to_width() 添加到管道的末尾时,问题就解决了。

使用上面示例的一部分,下面的代码行将自动调整列,然后调整大小以适应作为第二个参数给出的最大 table 宽度(以英寸为单位)(这里我要 1/ 2 英寸文档页边距):


mytable %>% autofit() %>% fit_to_width(7.5)

需要注意的是,对于我的一些 table,添加 fit_to_width() 函数会大大减慢渲染过程。 对于那些 tables,我使用了@bumbledore 的建议 set_table_properties(layout = "autofit") 并且效果很好(为了记录,我也使用默认设置的 officedown)。