incremental Shiny UI 使用 conditionalPanel() 和条件中的文本输出

incremental Shiny UI using conditionalPanel() and a text output in conditions

我一直在尝试创建一个 Shiny UI,它会根据数据处理的阶段而变化,但我无法弄清楚为什么我的条件面板不弹出,甚至我的文本也不弹出调试输出未在 UI.

中显示值

在这个小例子中,我希望能够在按下一个按钮后显示一个面板,然后在按下第二个按钮后显示另一个面板。如果用户再次按下第一个按钮,第二个面板应该消失。

library(shiny)

ui <- fluidPage(
    p("value of stage is:"),
    textOutput("stage"),
    actionButton("button1", "Show only the first panel"),
    conditionalPanel("output.stage == 'first' || output.stage == 'second'",
                     p("First panel."),
                     actionButton("button2", "Also show the second panel")),
    conditionalPanel("output.stage == 'second'",
                     p("Second panel."))
)

server <- function(input, output) {
  stage <- reactive({"initial"})
  stage <- eventReactive(input$button1, {"first"})
  stage <- eventReactive(input$button2, {"second"})
  output$stage <- renderText({stage()})
  # make stage always available to UI
  outputOptions(output, "stage", suspendWhenHidden = FALSE)
}

shinyApp(ui = ui, server = server)

我也尝试过使用 observeEvent(),但没有用。

编辑:我没有在我的条件中直接使用 input.button* 值,因为在我的用例中,stage 值还取决于其他因素发生在服务器上。

编辑以获得更好的解释:

您定义 stage 的次数过多。唯一算的是最后一个:

stage <- eventReactive(input$button2, {"second"})

在这一点上,stage只是那个,所以它永远不会触发。

这是您要搜索的内容:

library(shiny)

ui <- fluidPage(
  p("value of stage is:"),
  textOutput("stage"),
  actionButton("button1", "Show only the first panel"),
  conditionalPanel("output.stage == 'first' || output.stage == 'second'",
                   p("First panel."),
                   actionButton("button2", "Also show the second panel")),
  conditionalPanel("output.stage == 'second'",
                   p("Second panel.")),
  textOutput("stage_dependant")
)

server <- function(input, output) {
  
  button1_triggered <- reactiveVal(F)
  button2_triggered <- reactiveVal(F)
  
  observeEvent(input$button1,{
    button1_triggered(!button1_triggered()) ## assigning a new value to button1_triggered : its contrary
  })
  
  observeEvent(input$button2,{
    button2_triggered(!button2_triggered()) ## Invert the boolean
  })

  stage <- reactive({
    if(!button1_triggered() & !button2_triggered()){
      "intial"
    } else if(button1_triggered() & !button2_triggered()){
      "first"
    } else if(!button1_triggered() & button2_triggered()){
      "second anyways ?"
    } else {
      "second"
    }
  })
  
  output$stage <- renderText({stage()})
  # make stage always available to UI
  outputOptions(output, "stage", suspendWhenHidden = FALSE)

stage_dependant <- reactive({
        paste("This is a stage dependant reactive :",stage())
      })
    
      output$stage_dependant <- renderText(stage_dependant())
}



  

shinyApp(ui = ui, server = server)

你可以搜索更优雅的方式来定义stage,但是这样你应该明白原理了。

另请注意,使用 checkboxInput 似乎更适合此功能。