Skip to content

Instantly share code, notes, and snippets.

@tomsing1
Last active April 7, 2024 19:33
Show Gist options
  • Save tomsing1/884f32a3f40abd9a937dab0c54d23fda to your computer and use it in GitHub Desktop.
Save tomsing1/884f32a3f40abd9a937dab0c54d23fda to your computer and use it in GitHub Desktop.
Modularized shiny app using conditional panels (modified from the shiny::conditionalPanel help page)
# The following code is based on the shiny::conditionalPanel() help page. The `ui` and `server`
# components have been compartmentalized into the `mod_histogram` module. The `histogramApp`
# function shows an example of using this module.
# Note that the `ns = ns` argument needs to be passed ot the conditionalPanel() call.
library(shiny)
mod_histogram_ui <- function(id){
ns <- NS(id)
fluidPage(
sidebarPanel(
selectInput(ns("plotType"), "Plot Type",
c(Scatter = "scatter", Histogram = "hist")
),
# Only show this panel if the plot type is a histogram
conditionalPanel(
condition = "input.plotType == 'hist'",
ns = ns,
selectInput(
ns("breaks"), "Breaks",
c("Sturges", "Scott", "Freedman-Diaconis", "[Custom]" = "custom")
),
# Only show this panel if Custom is selected
conditionalPanel(
condition = "input.breaks == 'custom'",
ns = ns,
sliderInput(ns("breakCount"), "Break Count", min = 1,
max = 100, value = 10)
)
)
),
mainPanel(
plotOutput(ns("plot"))
)
)
}
mod_histogram_server <- function(id, df, labels, interactive = FALSE){
moduleServer( id, function(input, output, session){
x <- rnorm(1000)
y <- rnorm(1000)
output$plot <- renderPlot({
if (input$plotType == "scatter") {
plot(x, y)
} else {
breaks <- input$breaks
if (breaks == "custom") {
breaks <- input$breakCount
}
hist(x, breaks = breaks)
}
})
})
}
histogramApp <- function() {
ui <- mod_histogram_ui("histogram_1")
server <- function(input, output, session) {
mod_histogram_server("histogram_1")
}
shinyApp(ui, server)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment