Search code examples
rrshiny

Is there a way that add RShiny button but also keep the immediate action?


I am new to RShiny. I made a program and it works well. It contains a simulation function, and it can react immediately when the parameters change. However, I want to add a button that can use the parameter and run the simulation function again. Also, I want to keep the immediate reaction.

I create a similar sample.

library(shiny)

ui <- fluidPage(

# Application title
titlePanel("Testing"),

# Sidebar with a slider input for number of sample
sidebarLayout(
  sidebarPanel(
     sliderInput("n",
                 "Number:",
                 min = 1,
                 max = 10,
                 value = 5)
  ),
  
  # Show sample result
  mainPanel(
    textOutput("sample")
  )
 )
)

# Define server logic
server <- function(input, output) {

x <- c(1:100)

output$sample <- renderPrint({
 sample(x, input$n)
 })
}

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

Like in this sample, I sample N numbers from 1 to 100. The result can immediately change when slicebar change. In the meantime, I want to add a button that can re-sample N numbers again and get another result.

Which function should I select for the button in this situation? Thank you so much for your help!


Solution

  • You can add an action button and then move your data into a reactive element that is dependent on both the button and the input value. For example

    library(shiny)
    
    ui <- fluidPage(
      
      # Application title
      titlePanel("Testing"),
      
      # Sidebar with a slider input for number of sample
      sidebarLayout(
        sidebarPanel(
          sliderInput("n", "Number:", min = 1, max = 10, value = 5),
          actionButton("rerun", "Rerun")
        ),
        
        # Show sample result
        mainPanel(
          textOutput("sample")
        )
      )
    )
    
    # Define server logic
    server <- function(input, output) {
      
      x <- c(1:100)
      
      current_data <- reactive({
        input$rerun
        sample(x, input$n)
      })
      
      output$sample <- renderPrint({
        current_data()
      })
    }
    
    # Run the application 
    shinyApp(ui = ui, server = server)