For Loop for Creating Multiple Tables using knitr and kableExtra packages in RMarkdown
Asked Answered
C

1

4

I need to create multiple tables in RMarkdown and style it with the kableExtra package. As an example, I have the iris dataset. My first table displays the first 20 rows, my second table the next 20 rows, and my third table next 20 rows... Below is the code:

---
title: ""
output: pdf_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```     
```{r}
library(knitr)
library(kableExtra)

landscape(kable_styling(kable(iris[1:20, ], format = "latex", align = "c", 
     row.names = FALSE), latex_options = c("striped"), full_width = T))

landscape(kable_styling(kable(iris[21:40, ], format = "latex", align = "c", 
     row.names = FALSE), latex_options = c("striped"), full_width = T))

landscape(kable_styling(kable(iris[41:60, ], format = "latex", align = "c", 
     row.names = FALSE), latex_options = c("striped"), full_width = T))
```

It works well and it returns three tables, each one in a different sheet. In reality I have more than just three tables so I thought it would be a lot wiser to use a for loop and I made use of the answer given in this link R: why kable doesn't print inside a for loop?. Simple I put a line break after each print call as advised.

---
title: "untitled"
output: pdf_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
```{r}  

library(knitr)
library(kableExtra)

for (i in 1:3) {

  print(landscape(kable_styling(
    kable(iris[20*(i-1)+1:20*i, ], format = "latex", align = "c", 
          row.names = FALSE), latex_options = c("striped"), full_width = T)))
  cat("\n")
}
```

But it does not work. I guess that is because I encapsulated the kable command with the commands from the kableExtra package.

Is there who can make it work? I mean is there a way that can save me from typing?

Counterfoil answered 5/8, 2018 at 17:31 Comment(0)
R
4

Your existing code was nearly there. I think the only change needed is to add results='asis' to the chunk option (I don't think the extra newline is necessary). Here's the full RMarkdown content which works for me

---
output: pdf_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```     

```{r results='asis'}  
library(knitr)
library(kableExtra)
for (i in 1:3) {
  print(landscape(kable_styling(
    kable(iris[20*(i-1)+1:20*i, ], format = "latex", align = "c", 
          row.names = FALSE), latex_options = c("striped"), full_width = T)))
}
```
Ragan answered 7/8, 2018 at 4:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.