How to knit_print flextable with loop in a rmd file

旧时模样 提交于 2019-12-07 15:56:31

This is a limitation of one of the functions that flextable uses in its knit_print method: knitr::asis_output() can't be used in a loop. A couple of solutions are described here: https://github.com/yihui/knitr/issues/1137.

This one works for me in HTML output, just collecting all the output into one big vector and printing it at the end. I have modified the code to also insert some text before the table and a figure after it. I don't use Word, but I'd assume it will also work there:

---
output: html_document
---

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

```{r}
data(cars)
speed <- unique(cars$speed)
results <- character()
for (v in 1:length(speed)) {
  carspd <- cars[which(cars$speed == speed[v]),]
  tb <- regulartable(carspd)

  # Generate a figure in a temporary file
  filename <- tempfile(fileext = ".png")
  png(filename)
  hist(carspd$dist)
  dev.off()

  # Put everything into the results vector
  results <- c(results, "\n\nThis is the table for v =", v,
                        knit_print(tb),
                        knitr:::wrap(include_graphics(filename)))

}
asis_output(results)
knit_print(tb)
```

A couple of notes:

  • The \n\n in the text seems to be necessary to insert a line break.
  • The knitr:::wrap() function is an undocumented internal function in knitr, so there might be limitations that I don't know about, and this might fail in some future version of knitr.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!