Sar*_*rah 13 r flextable r-markdown
嗨,我正在尝试flextable在 Rmarkdown .doc 文档中使用来格式化我的表格。我喜欢flextable提供(但对其他类似包开放)的简单格式选项,但发现我认为应该是基本功能的东西并不总是有效。
我想让表格适合 word 文档的宽度,以便如果需要的文本将在一列内换行以适应,但如果页面上有可用空间,列将变宽,但不会达到该列的程度太宽以至于没有显示所有数据。
我在下面做了一个例子来说明我的问题。默认情况下,所有列都具有相同的宽度,并且文本会被换行以适应,但因此会浪费空间。我想将列拟合到数据中(使用autofit),但这会使列如此宽以至于它们从屏幕上消失。我希望使用mpg,vs和carb更广泛的快乐媒体,但仍在发生一些文本换行。例如我想要这个:
显然我可以手动更改宽度,flextable::width但我的表格是通过自动化过程制作的,所以我不知道我希望每列有多宽。
这是我的示例,它显示了 with 或 eithout 的问题 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()
```
Run Code Online (Sandbox Code Playgroud)
Sar*_*rah 17
我已经编写了一个函数来使表格适合现在工作良好的页面,尽管我仍然有点惊讶没有内置函数来执行此操作(例如)知道页面本身的宽度,所以如果有人知道任何仍然渴望听到的。
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)
}
Run Code Online (Sandbox Code Playgroud)
小智 11
我在使用该函数时遇到了类似的问题autofit()。当我将该函数添加fit_to_width()到管道末端时,它解决了问题。
使用上面示例的一部分,以下代码行将自动调整列,然后调整大小以适应作为第二个参数给出的最大表格宽度(以英寸为单位)(这里我将使用 1/2 英寸文档边距):
mytable %>% autofit() %>% fit_to_width(7.5)
Run Code Online (Sandbox Code Playgroud)
需要注意的是,对于我的一些表,添加该fit_to_width()函数会大大减慢渲染过程。对于这些表,我使用了 @bumbledore 的建议set_table_properties(layout = "autofit"),并且效果很好(根据记录,我还使用带有默认设置的 officedown)。
小智 7
仅供参考 - 我今天遇到了同样的问题并使用了您的代码(谢谢)。但它仍然困扰着我,因为我不能完全正确。我在 Officedown 软件包网站(同一作者;https://github.com/davidgohel/officedown)上注意到他们使用了,set_table_properties(layout = "autofit")所以我尝试了。无论出于何种原因,它都按预期工作!我也使用officedown默认设置,所以也许两者一起工作得很好。
| 归档时间: |
|
| 查看次数: |
5355 次 |
| 最近记录: |