Skip to content

Instantly share code, notes, and snippets.

@matt-dray
Created April 12, 2024 13:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matt-dray/ba5f22f008eb574d5d9722f70ace8e8b to your computer and use it in GitHub Desktop.
Save matt-dray/ba5f22f008eb574d5d9722f70ace8e8b to your computer and use it in GitHub Desktop.
An experiment to expand a nested list into Rmd sections, including a recursive function to remove blank (`""`) elements
---
title: "Autogenerating Rmd sections from a nested list"
output:
html_document:
code_folding: hide
---
```{r}
remove_blanks_recursively <- function(x) {
if (!is.list(x)) return(x)
x |>
purrr::discard(\(x) isTRUE(nchar(x) == 0)) |>
purrr::map(remove_blanks_recursively)
}
expand_list_to_rmd <- function(x) {
x <- remove_blanks_recursively(x)
h1_names <- names(x)
for (h1 in h1_names) {
cat("#", h1, "\n\n")
h1_is_list <- is.list(x[[h1]])
if (!h1_is_list) cat(x[[h1]], "\n\n")
if (h1_is_list) {
h2_names <- names(x[[h1]])
for (h2 in h2_names) {
cat("##", h2, "\n\n")
h2_is_list <- is.list(x[[h1]][[h2]])
if (!h2_is_list) cat(x[[h1]][[h2]], "\n\n")
if (h2_is_list) {
h3_names <- names(x[[h1]][[h2]])
for (h3 in h3_names) {
cat("###", h3, "\n\n")
h3_is_list <- is.list(x[[h1]][[h2]][[h3]])
if (!h3_is_list) cat(x[[h1]][[h2]][[h3]], "\n\n")
if (h3_is_list) warning("No evaluation at this depth.")
}
}
}
}
}
}
```
```{r results='asis'}
n = 10
x <- list(
x1 = lorem::ipsum_words(n),
y1 = list(y1.1 = lorem::ipsum_words(n)),
z1 = list(
z1.1 = list(
z1.1.1 = lorem::ipsum_words(n),
z1.1.2 = "",
z1.1.3 = lorem::ipsum_words(n)
),
z1.2 = list(
z1.2.1 = "",
z1.2.2 = lorem::ipsum_words(n),
z1.2.3 = lorem::ipsum_words(n)
)
)
)
expand_list_to_rmd(x)
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment