Created
July 29, 2022 03:59
-
-
Save MilesMcBain/e5864742a30b5890717b03779b312fa7 to your computer and use it in GitHub Desktop.
recurse_html.R
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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