首页 > 解决方案 > 用for循环显示多个kables?

问题描述

下面的 Rmarkdown 代码将两个表放在一个列表中,然后尝试使用 for 循环显示它们。

---
title: "Testing Section Numbers"
author: "Authors"
# Neither HTML nor PDF work.  To try PDF, uncomment:
# output: pdf_document
---

```{r pressure2, echo=FALSE}
library(knitr)
tables <- list(
  kable(pressure[1:5,], caption = "My first table"),
  kable(pressure[1:5,], caption = "My second table"))
```

first way works:
```{r pressure3a, echo=FALSE}
tables[[1]]
tables[[2]]
```

second way blank:
```{r pressure3b, echo=FALSE}
for (table in tables) {
  table
}
```

third way has raw text:
```{r pressure3c, echo=FALSE}
for (table in tables) {
  print(table)
}
```

fourth way badly formatted:
```{r pressure3d, echo=FALSE, results='asis'}
for (table in tables) {
  cat(table)
}
```

fifth way blank:
```{r pressure3e, echo=FALSE}
for (idx in 1:length(tables)) {
  table[[idx]]
}
```

第一种方式正确显示表格,但不是 for 循环。其他方法都行不通。

如何使用 for 循环在一个块中显示多个 kable?

我见过人们在几个 答案中使用 for 循环,所以我可能遗漏了一些简单的东西。

标签: r-markdownknitrkable

解决方案


你的第三种方法几乎是正确的;-)

只需使用该选项results = "asis"

```{r pressure3b, echo=FALSE, results='asis'}
for (table in tables) {
  print(table)
}
```

推荐阅读