首页 > 解决方案 > Shiny SidebarPanel selectInput 仅在选中复选框后

问题描述

我试图有一个闪亮的侧边栏面板,其中一个输入始终存在,一个仅在选中复选框后出现。我能找到的所有相关解决方案都在谈论在checkboxInput上使用 for 条件output,但我不确定如何实现这一点。为了显示我需要什么,这是我的代码片段:

require(shiny)


ui <- fluidPage(

    titlePanel('My App'),
    sidebarPanel(selectInput(inputId = "id1",
                         label = "something 1",
                         choices = c('a', 'b', 'c')),                 
             
                     checkboxInput("test_check", "Do you want to this?", value = FALSE),
                     uiOutput("test"), # checkbox to see if the user wants a comparison
             
                     selectInput(inputId = "id2",
                         label = "something2",
                         choices = c('a', 'b', 'c'))
    ),

    mainPanel(
        tabPanel("Some Info", htmlOutput(outputId = "info1"))
    ))

server <- function(input, output, session){}
shinyApp(ui = ui, server = server)

所以我希望id2只有在选中复选框时才出现在侧边栏中,但不知道该怎么做。谢谢。

编辑:添加了一个最小的可重现示例。

标签: rshinyshinydashboard

解决方案


您可以将一些 UI 移动到服务器以检查该框,这是当一个输入依赖于另一个输入时我所做的,那么您只需要使用 req()

ui <- fluidPage(
  
  titlePanel('My App'),
  sidebarPanel(selectInput(inputId = "id1",
                           label = "something 1",
                           choices = c('a', 'b', 'c')),                 
               
               checkboxInput("test_check", "Do you want to this?", value = FALSE),
               uiOutput("test"), # checkbox to see if the user wants a comparison
               uiOutput("id2")

  ),
  
  mainPanel(
    tabPanel("Some Info", htmlOutput(outputId = "info1"))
  ))

server <- function(input, output, session){
  output$id2 <- 
    renderUI({
      req(input$test_check)
      selectInput(inputId = "id2",
                  label = "something2",
                  choices = c('a', 'b', 'c'))
    })
  
}
shinyApp(ui = ui, server = server)

推荐阅读