Search code examples
rr-markdownkablekableextra

how to use a for loop in rmarkdown?


Consider this simple example:

---
title: "Untitled"
output: ioslides_presentation
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
## Slide with R Output
```{r t,  warning=FALSE, message=FALSE}

library(knitr)
library(kableExtra)
library(dplyr)

for(threshold in c(20, 25)) {
  cars %>% 
    filter(dist < threshold) %>%
    kable('html') %>% 
    kable_styling(bootstrap_options = "striped") 
}
```

Here I simply want to print each output of the for loop into a different slide. In this example, there are two calls to kablethat should go on two different slides.

The code above does not work. Am I even using the right packages for that? Any ideas?

Thanks!


Solution

  • You can use the asis option:

    ---
    title: "Untitled"
    output: ioslides_presentation
    ---
    
    ```{r setup, include=FALSE}
    knitr::opts_chunk$set(echo = FALSE)
    library(knitr)
    library(kableExtra)
    library(dplyr)
    # needed so r will include javascript/css dependencies needed for striped tables:
    kable(cars, "html") %>% kable_styling(bootstrap_options = "striped")
    ```
    
    ```{r, results = "asis"}
    for (threshold in c(20, 25)) {
      cat("\n\n##\n\n")
      x <- cars %>%
        filter(dist < threshold) %>%
        kable('html') %>%
        kable_styling(bootstrap_options = "striped")
      cat(x)
    }
    ```