闪亮:如何使反应性值初始化为默认值

36

考虑以下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")
  )
))
在此示例中,在操作按钮被按下之前,右侧面板为空。我希望默认值为“50”的文本被默认呈现。如何在操作按钮还没有被按下时显示默认输入?

只有当 input$goButton>0 时,您才能将 nText 设置为 input$n,否则显示50。 - Dean MacGregor
2个回答

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接