Search code examples
rr-markdownknitrkable

Display multiple kables with a for loop?


The Rmarkdown code below puts two tables in a list, then tries to show them with a for loop.

---
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]]
}
```

The first way displays the tables properly, but is not a for loop. The other ways do not work.

How do I display multiple kables in one chunk with a for loop?

I've seen people use for loops in several answers, so I may be missing something simple.


Solution

  • Your third approach was almost right ;-)

    Just use the option results = "asis"

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