Search code examples
rshinyshiny-servershinyapps

How to trigger the same plot with two different actionButton but not repeating the whole function in shinyapp?


I want to have an example for users to use before actually running the app, just as I added a runexample button in the following code. But for this button, I don't want to write a repeated code to realize the same function than the other button. What's a good way to do it?


library(shiny)

# Define UI for application that draws a histogram
ui <- fluidPage(
   
   # Application title
   titlePanel("Old Faithful Geyser Data"),
   
   # Sidebar with a slider input for number of bins 
   sidebarLayout(
      sidebarPanel(
         sliderInput("bins",
                     "Number of bins:",
                     min = 1,
                     max = 50,
                     value = 30),
         actionButton("run","run"),
         actionButton("runExample","runExample")
         ),
   
      # Show a plot of the generated distribution
      mainPanel(
       
         plotOutput("distPlot")
      )
   )
)

# Define server logic required to draw a histogram
server <- function(input, output) {
   
  plot <- eventReactive(input$run,{
    x    <- faithful[, 2] 
    bins <- seq(min(x), max(x), length.out = input$bins + 1)
    hist(x, breaks = bins, col = 'darkgray', border = 'white')
  })
 
   output$distPlot <- renderPlot({
     plot()
      
   })
   
}

# Run the application 
shinyApp(ui = ui, server = server)


Solution

  • Would something like this work?

    Check the documentation (duelling buttons). I set 30 as default bins value for the runExample case directly in the observeEvent function but you could define this value somewhere else.

    ui <- fluidPage(
      
      # Application title
      titlePanel("Old Faithful Geyser Data"),
      
      # Sidebar with a slider input for number of bins 
      sidebarLayout(
        sidebarPanel(
          sliderInput("bins",
                      "Number of bins:",
                      min = 1,
                      max = 50,
                      value = 30),
          actionButton("run","run"),
          actionButton("runExample","runExample")
        ),
        
        # Show a plot of the generated distribution
        mainPanel(
          
          plotOutput("distPlot")
        )
      )
    )
    
    # Define server logic required to draw a histogram
    server <- function(input, output) {
      
      x    <- faithful[, 2] 
      v <- reactiveValues(data = NULL)
      
      observeEvent(input$run, {
          v$bins <- seq(min(x), max(x), length.out = input$bins + 1)
      })
      
      observeEvent(input$runExample, {
        v$bins <- seq(min(x), max(x), length.out = 30 + 1)
      }) 
      
    
      output$distPlot <- renderPlot({
        hist(x, breaks = v$bins, col = 'darkgray', border = 'white')
        
      })
      
    }
    
    # Run the application 
    shinyApp(ui = ui, server = server)