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

时间:2015-11-11 23:50:26

标签: 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()
  })
})

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")
  )
))

在此示例中,在按下操作按钮之前,右侧面板为空。我会喜欢使用默认值&#34; 50&#34;默认情况下呈现。

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

2 个答案:

答案 0 :(得分:11)

    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()
         }
      })
    })

答案 1 :(得分:9)

eventReactive也会记录here 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)