【问题标题】:Looping Flextables in R Markdown documents with Word output使用 Word 输出在 R Markdown 文档中循环 Flextables
【发布时间】:2020-01-30 02:33:54
【问题描述】:

我希望在单个 R Markdown 文档中打印多个 flextable。这在使用 html 输出时并不具有挑战性,但我需要 Word 输出。

使用 html 输出,以下 R Markdown 代码(取自 https://davidgohel.github.io/flextable/articles/offcran/examples.html#looping-in-r-mardown-documents 的示例)生成一个包含多个 Flextable 的文档:

---
output:
  html_document: default

---

```{r}
library(htmltools)
library(flextable)

ft <- flextable(head(iris))
tab_list <- list()
for(i in 1:3){
  tab_list[[i]] <- tagList(
    tags$h6(paste0("iteration ", i)),
    htmltools_value(ft)
  )
}
tagList(tab_list)
```

我无法使用 Word 文档输出获得等效的输出。 中提出的解决方案 How to knit_print flextable with loop in a rmd file 同样适用于 html 输出,但我无法让它在 Word 输出中正确呈现。

任何与上述示例等效的 R Markdown Word 文档输出的建议都会非常有帮助!

【问题讨论】:

  • 是否循环,我希望有人能提供比我知道的更好的方法来为 Word(或其他非 LaTeX 文字处理器)制作表格。

标签: r r-markdown knitr flextable


【解决方案1】:

您需要使用flextable::docx_value 和块选项results='asis'

---
title: "Untitled"
output: word_document
---

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

```{r results='asis'}
ft <- flextable(head(iris))
for(i in 1:3){
  cat("<w:p/>")## add this to add an empty  new paragraph between tables
  flextable::docx_value(ft)
}
```

【讨论】:

  • 直接来自软件包开发者!不错!