簡體   English   中英

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

[英]Using flextable in r markdown loop not producing tables

我有很多表要創建,並且正在嘗試在循環中創建它們。 我在 rstudio 中使用帶有 rmarkdown 的 flextable。 在循環中使用print(theFlextable)命令會生成文本列表而不是表格。 這發生在 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")
}
``` 

這是上面最后一個塊的 word 輸出:

類型:彈性對象。 col_keys: Sepal.Length, Sepal.Width, Petal.Length, Petal.Width, Species header has 1 row(s) body has 10 row(s) 原始數據集樣本: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.

類型:彈性對象。 col_keys: Sepal.Length, Sepal.Width, Petal.Length, Petal.Width, Species header has 1 row(s) body has 10 row(s) 原始數據集樣本:Sepal.Length Sepal.Width Petal.Length Petal.Width Species 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 53265 弗吉尼亞州

如果您有Pandoc版本> = 2(與RStudio 1.2捆綁在一起),您可以使用knit_print 我發現

cat(knit_print(ft))

成功地在循環中打印表。

我不確定這是否是正確答案,但我用它來解決我的問題:

循環遍歷knitr和rmarkdown中的代碼

在 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。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM