0

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!

  • It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. It's not clear what you are describing at the moment. – MrFlick Jun 25 '21 at 01:51
  • @MrFlick, thank you for your reminder! I created a similar sample and hope it can help. – Cissy Yang Jun 25 '21 at 02:26

1 Answers1

0

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)
MrFlick
  • 195,160
  • 17
  • 277
  • 295