Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping Flextables in R Markdown documents with Word output

I am looking to print multiple flextables in a single R Markdown document. This is not challenging when using html output, but I need Word output.

With html output, the following R Markdown code (example taken from https://davidgohel.github.io/flextable/articles/offcran/examples.html#looping-in-r-mardown-documents) produces a document with multiple 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)
```

I have been unable to get an equivalent output using Word document output. The solution proposed in How to knit_print flextable with loop in a rmd file similarly works fine with html output, but I have failed to get this to render correctly with Word output.

Any advice on a R Markdown Word document output equivalent of the above example would be very helpful!

like image 242
MLevine Avatar asked Sep 30 '19 19:09

MLevine


1 Answers

You need to use flextable::docx_value and the chunk option 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)
}
```
like image 57
David Gohel Avatar answered Nov 17 '22 21:11

David Gohel