Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using flextable in r markdown loop not producing tables

I have many tables to create and am trying to create them in a loop. I'm using flextable with rmarkdown inside rstudio. Using print(theFlextable) command in a loop produces a list of text rather than the table. This happens for docx and html output types. If I don't use a loop flextable renders correctly. Here is a demo:

---
title: "Demo"
output: word_document
---

```{r setup, include=FALSE}
library(flextable)
```
## This Works
```{r iris, echo=F, message=F, error=F, results='asis'}
ft<-flextable(iris[1:10,])
ft
```
## This produces no output
```{r echo=F, message=F, error=F, results='asis'}
doThese<-c("setosa","virginica")
for (i in doThese){
  tbl<-subset(iris, Species==i)
  ft<-flextable(tbl[1:10,])
  ft
}
```
## This produces incorrect output
```{r echo=F, message=F, error=F, results='asis'}
doThese<-c("setosa","virginica")
for (i in doThese){
  tbl<-subset(iris, Species==i)
  ft<-flextable(tbl[1:10,])
  print(ft)
  cat("\n\n")
}
``` 

This is the output in word of the last block above:

type: flextable object. col_keys: Sepal.Length, Sepal.Width, Petal.Length, Petal.Width, Species header has 1 row(s) body has 10 row(s) original dataset sample: Sepal.Length Sepal.Width Petal.Length Petal.Width Species 1 5.1 3.5 1.4 0.2 setosa 2 4.9 3.0 1.4 0.2 setosa 3 4.7 3.2 1.3 0.2 setosa 4 4.6 3.1 1.5 0.2 setosa 5 5.0 3.6 1.4 0.2 setosa

type: flextable object. col_keys: Sepal.Length, Sepal.Width, Petal.Length, Petal.Width, Species header has 1 row(s) body has 10 row(s) original dataset sample: Sepal.Length Sepal.Width Petal.Length Petal.Width Species 101 6.3 3.3 6.0 2.5 virginica 102 5.8 2.7 5.1 1.9 virginica 103 7.1 3.0 5.9 2.1 virginica 104 6.3 2.9 5.6 1.8 virginica 105 6.5 3.0 5.8 2.2 virginica

like image 616
user2547973 Avatar asked Oct 05 '18 17:10

user2547973


2 Answers

If you have Pandoc version >= 2 (bundled with RStudio 1.2) you can use knit_print. I found

cat(knit_print(ft))

successfully printed the tables in a loop.

like image 58
anotherfred Avatar answered Nov 10 '22 01:11

anotherfred


We often need to loop through data to create subtables in RMarkdown. Here is a straightforward solution for flextable:

```{r, report3, results='asis'}

doThese<-c("setosa","virginica")

for (i in doThese) {
  tbl<-subset(iris, Species==i)
  ft <- flextable(tbl[1:10,])
  flextable_to_rmd(ft)
}
 
```

The key takeaways: set results="asis" for the code chunk, and use flextable_to_rmd function instead of print or cat.

like image 37
GGAnderson Avatar answered Nov 09 '22 23:11

GGAnderson