在 r markdown 循环中使用 flextable 不生成表格

Using flextable in r markdown loop not producing tables

我有很多 table 要创建,我正在尝试循环创建它们。我在 rstudio 中使用 flextable 和 rmarkdown。在循环中使用 print(theFlextable) 命令会生成一个文本列表,而不是 table。这发生在 docx 和 html 输出类型上。如果我不使用循环,flextable 会正确呈现。这是一个演示:

---
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")
}
``` 

这是上面最后一个块的字输出:

类型:flextable 对象。 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 物种 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

类型:flextable 对象。 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 物种 101 6.3 3.3 6.0 2.5 弗吉尼亚 102 5.8 2.7 5.1 1.9 弗吉尼亚 103 7.1 3.0 5.9 2.1 弗吉尼亚 104 6.3 2.9 5.6 1.8 弗吉尼亚 105 6.5 82 3.0

我不确定这是否是正确答案,但我用它来解决我的问题:

Looping through code in knitr and rmarkdown

如果您的 Pandoc 版本 >= 2(与 RStudio 1.2 捆绑在一起),您可以使用 knit_print。我发现

cat(knit_print(ft))

成功循环打印表格。

我们经常需要循环遍历数据以在 RMarkdown 中创建子表。这是 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)
}
 
```

关键要点:为代码块设置 results="asis",并使用 flextable_to_rmd 函数而不是 print 或 cat。