闪亮:如何使用默认值初始化无功值

Eri*_*ric 18 r shiny

请考虑以下actionButton演示:http://shiny.rstudio.com/gallery/actionbutton-demo.html

server.R:

shinyServer(function(input, output) {

  # builds a reactive expression that only invalidates 
  # when the value of input$goButton becomes out of date 
  # (i.e., when the button is pressed)
  ntext <- eventReactive(input$goButton, {
    input$n
  })

  output$nText <- renderText({
    ntext()
  })
})
Run Code Online (Sandbox Code Playgroud)

ui.R:

shinyUI(pageWithSidebar(
  headerPanel("actionButton test"),
  sidebarPanel(
    numericInput("n", "N:", min = 0, max = 100, value = 50),
    br(),
    actionButton("goButton", "Go!"),
    p("Click the button to update the value displayed in the main panel.")
  ),
  mainPanel(
    verbatimTextOutput("nText")
  )
))
Run Code Online (Sandbox Code Playgroud)

在此示例中,在按下操作按钮之前,右侧面板为空.我宁愿在默认情况下渲染默认值为"50"的文本.

如果尚未按下操作按钮,如何使用默认输入显示输出?

小智 13

eventReactive此处ignoreNULL记录一点,它允许您在没有if语句的情况下初始化对象.

通过添加,ignoreNULL = FALSE到原始帖子(给出或采取一些格式),verbatimTextOutput启动时显示50.

这让我觉得服务器端有点经济.

ui <- fluidPage(titlePanel("actionButton test"),
                sidebarLayout(
                  sidebarPanel(
                    numericInput(
                      "n",
                      "N:",
                      min = 0,
                      max = 100,
                      value = 50
                    ),
                    br(),
                    actionButton("goButton", "Go!"),
                    p("Click the button to update the value displayed in the main panel.")
                  ),
                  mainPanel(verbatimTextOutput("nText"))
                ))

server <- function(input, output) {

  ntext <- eventReactive(input$goButton, {
    input$n
  }
  # Adding this parameter to the original example makes it work as intended
  # with 50 in the output field to begin with
  , ignoreNULL = FALSE
  )

  output$nText <- renderText({
    ntext()
  })
}

shinyApp(ui = ui, server = server)
Run Code Online (Sandbox Code Playgroud)


小智 12

    shinyServer(function(input, output) {
      values <- reactiveValues(default = 0)

      observeEvent(input$goButton,{
           values$default <- input$goButton
      })
      # builds a reactive expression that only invalidates 
      # when the value of input$goButton becomes out of date 
      # (i.e., when the button is pressed)
      ntext <- eventReactive(input$goButton, {
           input$n
      })

      output$nText <- renderText({
         if(values$default == 0){
              50
         }
         else{
            ntext()
         }
      })
    })
Run Code Online (Sandbox Code Playgroud)