Search code examples
rloopsr-markdownbookdown

How to programmatically generate tabs in Rmarkdown?


I would like to create an html report using Rmarkdown where the results are displayed in panelsets.

I can create the panelset, but the plots always end up in the second tab, the first remains empty.

Does anyone have an idea what I am doing wrong? Here is my code so far with sample data:

```{r sepal_loop, results='asis', echo=FALSE}
library(dplyr)
library(ggplot2)

df <- datasets::iris %>%
  dplyr::as_tibble()

for (i in c("setosa", "versicolor", "virginica")) {
  p <- df %>%
    dplyr::filter(Species == i) %>%
    ggplot2::ggplot(ggplot2::aes(Sepal.Length, Petal.Length)) +
    ggplot2::geom_point()
  
  q <- df %>%
    dplyr::filter(Species == i) %>%
    ggplot2::ggplot(ggplot2::aes(Sepal.Width, Petal.Width)) +
    ggplot2::geom_point()
  
  cat(paste0("\n\n## ", i, "\n"))
  cat("#### {.panelset -}\n")
  cat("##### Length {-}\n")
  cat("##### Width {-}\n")
  print(p)
  print(q)
}
```

This is what it looks like so far: Tab "Length" is empty

And if I then click on the tab "Width"... Tab "Width" contains both plots

When I print the plots under the specific header

  cat(paste0("\n\n## ", i, "\n"))
  cat("#### {.panelset -}\n")
  cat("##### Length {-}\n")
  print(p)
  cat("##### Width {-}\n")
  print(q)

This is my result:

No "Width"-tab


Solution

  • Here is the full example working for me

    ---
    title: "Untitled"
    output: html_document
    date: '2022-09-05'
    ---
    
    ```{r setup, include=FALSE}
    knitr::opts_chunk$set(echo = TRUE)
    library(dplyr)
    library(ggplot2)
    ```
    
    ```{r sepal_loop, results='asis', echo=FALSE}
    df <- datasets::iris %>%
      dplyr::as_tibble()
    
    for (i in c("setosa", "versicolor", "virginica")) {
      p <- df %>%
        dplyr::filter(Species == i) %>%
        ggplot2::ggplot(ggplot2::aes(Sepal.Length, Petal.Length)) +
        ggplot2::geom_point()
      
      q <- df %>%
        dplyr::filter(Species == i) %>%
        ggplot2::ggplot(ggplot2::aes(Sepal.Width, Petal.Width)) +
        ggplot2::geom_point()
      
      cat(paste0("# ", i, "{.tabset} \n\n"))
      
      cat("## Length \n\n")
      print(p)
      cat('\n\n')
      
      cat("## Width \n\n")
      print(q)
      cat('\n\n')
    }
    ```