Skip to content

Instantly share code, notes, and snippets.

@yjunechoe
Created January 13, 2023 03:56
Show Gist options
  • Save yjunechoe/3068f909b382a887cbb1852e126a4b4f to your computer and use it in GitHub Desktop.
Save yjunechoe/3068f909b382a887cbb1852e126a4b4f to your computer and use it in GitHub Desktop.
Minimal nested select input with {shinyTree}
library(shiny)
library(shinyTree)
library(highcharter)
library(dplyr)
pokemon_df <- highcharter::pokemon |>
select(primary = type_1, secondary = type_2, pokemon) |>
mutate(secondary = coalesce(secondary, primary))
pokemon_list <- shinyTree::dfToTree(pokemon_df)
ui <- fluidPage(
titlePanel("Minimal nested select input with {shinyTree}"),
sidebarLayout(
sidebarPanel(
actionButton("plot_button", "Plot:"),
shinyTree("pokemon_tree", checkbox = TRUE, themeIcons = FALSE)
),
mainPanel(
highchartOutput("pokemon_treemap")
)
)
)
server <- function(input, output, session) {
# Shiny Tree variable selection logic
output$pokemon_tree <- renderTree({ list(All = structure(pokemon_list, stselected = TRUE, stopened = TRUE)) })
# Reactive on tree state (incl. opened and closed subtrees) and terminal node selections
pokemon_tree_selected <- reactive({
unlist(get_selected(input$pokemon_tree), use.names = FALSE)
})
pokemon_selected <- reactive({
intersect(pokemon_df$pokemon, pokemon_tree_selected())
})
# Highchart treemap render logic
output$pokemon_treemap <- renderHighchart({
input$plot_button
pokemon_df |>
filter(pokemon %in% isolate(pokemon_selected())) |>
count(primary, secondary) |>
data_to_hierarchical(
group_vars = c("primary", "secondary"), size_var = "n"
) |>
hchart(type = "treemap")
})
}
shinyApp(ui, server)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment