【问题标题】:Shiny: How to make reactive value initialize with default valueShiny:如何使用默认值初始化反应值
【发布时间】:2016-02-13 05:19: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”的文本。

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

【问题讨论】:

  • 您可以将nText 设置为input$n 仅当input$goButton&gt;0 否则显示50。

标签: r shiny


【解决方案1】:

eventReactive 还采用ignoreNULL 作为记录的here,它允许您在没有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)

【讨论】:

    【解决方案2】:
        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()
             }
          })
        })
    

    【讨论】:

      猜你喜欢
      • 2017-11-22
      • 1970-01-01
      • 2019-02-15
      • 2017-12-18
      • 1970-01-01
      • 1970-01-01
      • 2012-05-15
      • 1970-01-01
      • 2014-12-29
      相关资源
      最近更新 更多