嗨,我正在尝试在Rmarkdown .doc文档中使用flextable格式化表格。我喜欢flextable提供的简单格式设置选项(但可以打开其他类似的程序包),但是发现我认为应该是基本功能的某些功能并不总是有效。

我想使表格适合word文档的宽度,以便在需要时将文本换行以适合列,但如果页面上有可用空间,则列会变宽,但不能超出列的范围太宽以至于无法显示所有数据。

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

r - Rmarkdown到word doc中的flextable autofit使表格超出页边距-LMLPHP

显然,我可以使用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()



```

最佳答案

我写了一个函数来使表格适合当前工作的页面,尽管令我感到有些惊讶的是,没有内置函数可以做到这一点(例如),它可以知道页面本身的宽度,因此,如果有人知道仍然想听听。

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

09-04 20:09