Skip to content

Instantly share code, notes, and snippets.

@MilesMcBain
Created July 29, 2022 03:59
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 MilesMcBain/e5864742a30b5890717b03779b312fa7 to your computer and use it in GitHub Desktop.
Save MilesMcBain/e5864742a30b5890717b03779b312fa7 to your computer and use it in GitHub Desktop.
recurse_html.R
library(tibble)
library(purrr)
library(tidyr)
library(htmltools)
library(dplyr)
df <- tibble::tribble(
~level_1, ~level_2, ~level_3,
"coffee", "espresso", "with milk",
"coffee", "espresso", "without milk",
"coffee", "filter", NA,
"tea", "green", NA,
"tea", "black", NA,
"water", NA, NA
)
nested_df <-
df |>
group_by(level_1, level_2) |>
nest() |>
group_by(level_1) |>
nest()
make_html <- function(input) {
if(is.vector(input) && length(input) == 1 && is.na(input)) return(NULL)
if (all(is.na(input[,1]))) return(NULL)
if (ncol(input) == 2) {
tag(
"ul",
pmap(input, function(...) {
name <- ..1
data <- ..2
tagList(
if (!is.na(name)) tag("li", name) else NULL,
make_html(data)
)
})
)
} else {
lapply(input[,1], \(x) { tag("li", x) })
}
}
make_html(nested_df)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment