Skip to content

Instantly share code, notes, and snippets.

@dantonnoriega
Last active January 8, 2022 19:22
Show Gist options
  • Save dantonnoriega/61559f39c06df92cca1f594bc63bcb8f to your computer and use it in GitHub Desktop.
Save dantonnoriega/61559f39c06df92cca1f594bc63bcb8f to your computer and use it in GitHub Desktop.
Loop to auto build flexdashboard content, specifically columns with tabs where each tab is an htmlwidget (like highcharts). Be sure to look at the raw code.
---
title: "Loop to Auto Build Tabs Containing htmlwidgets"
output: flexdashboard::flex_dashboard
---
```{r setup, echo =FALSE, eval = TRUE}
library(tidyverse)
library(flexdashboard)
library(highcharter)
labels <- mtcars %>% names # these will serve as labels for each tab
# create a bunch of random, nonsensical line graphs
hcs <- purrr::map(.x = mtcars, ~highcharter::hchart(mtcars, y = .x, type = 'line')) %>%
setNames(labels) # assign names to each element to use later as tab titles
```
Page
====================
Column {.tabset .tabset-fade}
-----------------------------
<!-- loop to build each tabs (in flexdashboard syntax) -->
<!-- each element of the list object `out` is a single tab written in rmarkdown -->
<!-- you can see this running the next chunk and typing `cat(out[[1]])` -->
```{r, echo = FALSE, eval = TRUE}
out <- lapply(seq_along(hcs), function(i) {
a1 <- knitr::knit_expand(text = sprintf("### %s\n", names(hcs)[i])) # tab header, auto extracts names of `hcs`
a2 <- knitr::knit_expand(text = "\n```{r}") # start r chunk
a3 <- knitr::knit_expand(text = sprintf("\nhcs[[%d]]", i)) # extract graphs by "writing" out `hcs[[1]]`, `hcs[[2]]` etc. to be rendered later
a4 <- knitr::knit_expand(text = "\n```\n") # end r chunk
paste(a1, a2, a3, a4, collapse = '\n') # collapse together all lines with newline separator
})
```
<!-- source: https://goo.gl/fnfXuO -->
<!-- As I mentioned in the SO post, I don't quite understand why it has to be -->
<!-- 'r paste(knitr::knit(...)' sometimes vs 'r knitr::knit(...)' but oh well -->
`r knitr::knit(text = paste(out, collapse = '\n'))`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment