Reputation: 1059
So I am building an R Shinny app that runs a simulation study and so every time the user changes one of the inputs I don't want the app to start running the simulations until they hit a submit button. How can I achieve this?
Here is the code I have so far:
The UI file:
#ui.R
# Define UI for random distribution application
shinyUI(fluidPage(
# Application title
titlePanel("ORR Simulator"),
# Sidebar with controls to select the random distribution type
# and number of observations to generate. Note the use of the
# br() element to introduce extra vertical spacing
sidebarLayout(
sidebarPanel(
fileInput('file1', 'Select the XXX.csv file',
accept=c('text/csv','text/comma-separated-values,text/plain','.csv')),
tags$hr(),
fileInput('file2', 'Select the YYY.csv file',
accept=c('text/csv','text/comma-separated-values,text/plain','.csv')),
tags$hr(),
numericInput("S", "Number of simulations to run:", 100),
mainPanel(
plotOutput("plot")
)
)
))
And so I would like for there to be a button that says something like submit and once they push that the actual R programs runs rather than running as soon as they change any input.
Upvotes: 5
Views: 7499
Reputation: 723
I had the same problem as you. Shiny waited for the first submit and when I typed a text a second time it immedialtely began to calculate. The solution I found is easy. Instead of using observeEvent you need to use eventReactive. I found it here
library(shiny)
ui <- fluidPage(
headerPanel("Example eventReactive"),
mainPanel(
# input field
textInput("user_text", label = "Enter some text:", placeholder = "Please enter some text."),
# submit button
actionButton("submit", label = "Submit"),
# display text output
textOutput("text"))
)
server <- function(input, output) {
# reactive expression
text_reactive <- eventReactive( input$submit, {
input$user_text
})
# text output
output$text <- renderText({
text_reactive()
})
}
shinyApp(ui = ui, server = server)
Upvotes: 6
Reputation: 1027
On the UI side you want to use something like actionButton
. On the server side you want to use an observe
or an observeEvent
.
ui.R:
library(shiny)
shinyUI(
fluidPage(
titlePanel("submit button example"),
column(4,
textInput(
inputId = "location_id",
label = "Enter stuff: ",
value = "param1"
),
actionButton(
inputId = "submit_loc",
label = "Submit"
)
)
)
)
server.R:
library(shiny)
shinyServer(
function(input, output, session) {
observeEvent(
eventExpr = input[["submit_loc"]],
handlerExpr = {
print("PRESSED") #simulation code can go here
}
)
}
)
With this setup, your simulation code only runs when shiny detects a change with the actionButton
. Your other inputs can be changed without triggering the simulation code to run -- you can change the textInput
and it won't trigger any of the simulation code to run.
Also note, the print
statement will not show up directly in the shiny app, it'll show up in your R console.
Upvotes: 7