如何让 Shiny 等到你点击提交

Rus*_*ian 4 r shiny

所以我正在构建一个运行模拟研究的 R Shinny 应用程序,所以每次用户更改其中一个输入时,我不希望应用程序开始运行模拟,直到他们点击提交按钮。我怎样才能做到这一点?

这是我到目前为止的代码:

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")
    )
  )
))
Run Code Online (Sandbox Code Playgroud)

所以我希望有一个按钮,上面写着诸如提交之类的东西,一旦他们按下,实际的 R 程序就会运行,而不是在更改任何输入后立即运行。

div*_*ero 6

在 UI 方面,您想使用类似actionButton. 在服务器端,您要使用observeobserveEvent.

用户界面:

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"
      )
    )
  )
)
Run Code Online (Sandbox Code Playgroud)

服务器.R:

library(shiny)
shinyServer(
  function(input, output, session) {
    observeEvent(
      eventExpr = input[["submit_loc"]],
      handlerExpr = {
        print("PRESSED") #simulation code can go here
      }
    )
  }
)
Run Code Online (Sandbox Code Playgroud)

使用此设置,您的模拟代码仅在 Shiny 检测到actionButton. 您可以在不触发模拟代码运行的情况下更改其他输入——您可以更改textInput并且它不会触发任何模拟代码运行。

另请注意,该print语句不会直接显示在闪亮的应用程序中,它会显示在您的 R 控制台中。


小智 5

我和你有同样的问题。Shiny 等待第一次提交,当我第二次输入文本时,它立即开始计算。我找到的解决方案很简单。您需要使用eventReactive,而不是使用observeEvent。我在这里找到的

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)
Run Code Online (Sandbox Code Playgroud)