有条件地切换从 Rmarkdown 代码生成的 MS Word 文档的页面布局

问题描述 投票:0回答:1

我使用 Rmarkdown 和 Officedown 包创建 MS Word 文档。我的输出是

officdown::rdocx_document
。 我的 Rmarkdown 文件中有这样的代码:

library(flextable)
library(officer)

tables <- list(
  flextable(iris),
  flextable(mtcars)
  # and potentially more tables, the list is dynamic
)

我想根据每个表的列数切换纵向/横向布局。例如,如果列数大于 5,则页面方向应为横向,否则为纵向。

我知道

officer
包提供了
block_section
功能,但我不知道如何动态使用它。请注意,我不知道会有多少张桌子,列表是动态的。

我尝试了这个,根据block_section函数的帮助页面:

orients <- calculate_page_orient(tables)  # a helper that will determine the orientation based on the number of columns in a table
for (i in seq_len(lenght(tables))) {
  block_section(prop_section(type = "continuous")
  tables[[i]]
  block_section(prop_section(page_size = page_size(orient = orients[i])))
}

但这不起作用。如何使用officer包动态设置页面布局?

r ms-word r-markdown officer officedown
1个回答
0
投票

这是一种可能的实现,它不是使用

block_section
,而是使用
!---BLOCK_LANDSCAPE_START/END--->
将页面布局设置为横向,并使用块选项
results='asis'
for
循环中动态渲染表格。另请注意,我直接循环数据集并在循环内转换为
flextable

---
output: officedown::rdocx_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, fig.cap = TRUE)
library(officedown)
library(officer)
library(flextable)
```

```{r}
tables <- list(
  iris,
  mtcars
) |> 
  lapply(head)
```

```{r}
calculate_page_orient <- function(x) {
  if (ncol(x) > 5) "landscape" else "portrait"
}
```

```{r results='asis'}
for (tbl in tables) {
  orient <- calculate_page_orient(tbl)
  if (orient == "landscape") cat("\n\n<!---BLOCK_LANDSCAPE_START--->\n\n")
  ft <- flextable(tbl)
  ft <- autofit(ft)
  flextable_to_rmd(ft)
  if (orient == "landscape") cat("\n\n<!---BLOCK_LANDSCAPE_STOP--->\n")
  cat("\\newpage\n\n")
}
```

© www.soinside.com 2019 - 2024. All rights reserved.