使用 Word 输出在 R Markdown 文档中循环 Flextables

MLe*_*ine 5 r flextable knitr r-markdown

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

对于 html 输出,以下 R Markdown 代码(示例取自https://davidgohel.github.io/flextable/articles/offcran/examples.html#looping-in-r-mardown-documents)生成具有多个 Flextables 的文档:

---
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)
```
Run Code Online (Sandbox Code Playgroud)

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

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

Dav*_*hel 5

您需要使用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)
}
```
Run Code Online (Sandbox Code Playgroud)