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

不羁的心 提交于 2019-12-08 02:39:20

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/51696689/for-loop-for-creating-multiple-tables-using-knitr-and-kableextra-packages-in-rma

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!