How to add a conditional 'selectInput' based on a selected checkboxInput in shiny?

前端 未结 1 766
耶瑟儿~
耶瑟儿~ 2021-01-24 11:26

I would like that if the checkboxInput Factorial parameters is selected, this would do the app to show a new selectInput with several option. Here is

1条回答
  •  温柔的废话
    2021-01-24 11:31

    Update

    I figured it out! edit as follows:

    conditionalPanel(condition = "input.fixed == 1",

    Previous answers

    Generally, you would need input.fixed in a conditionalPanel although this doesn't seem to work for checkboxInput for some reason (maybe someone else can explain why?). There are a few alternatives. I would suggest the shinyjs package.

    library(shiny)
    library(shinyjs)
    ui <- fluidPage(
      useShinyjs(),
      titlePanel("Old Faithful Geyser Data"),
      sidebarLayout(
        sidebarPanel(
          sliderInput("bins",
                      "Number of bins:",
                      min = 1,
                      max = 50,
                      value = 30),
          checkboxInput("fixed", "Factorial parameters"),
          hidden(selectInput("choice",
                             "Choose your fixed parameter", 
                             c("alpha"= "Alpha", "beta"="Beta"),
                             selected = "alpha"))
        )
        ,
        mainPanel(
          plotOutput("distPlot")
        )
      )
    )
    
    
    server <- function(input, output) {
    
      output$distPlot <- renderPlot({
    
        x    <- faithful[, 2] 
        bins <- seq(min(x), max(x), length.out = input$bins + 1)
        hist(x, breaks = bins, col = 'darkgray', border = 'white')
        observeEvent(input$fixed, {
          toggle("choice")
        }, ignoreInit = TRUE)
      })
    }
    
    
    shinyApp(ui = ui, server = server)
    

    Instead of toggle you could be more explicit with an if...else statement using shinysj::show() and shinyjs::hide() although I think this is neater (just note the ignoreInit = TRUE).

    As mentioned above using checkboxGroupInput for example seems to work with conditionalPanels:

    checkboxGroupInput("fixed", label = "", choices = "Factorial parameters"),
        conditionalPanel(condition = "input.fixed == 'Factorial parameters'",
                         selectInput("choice",
                                     "Choose your fixed parameter", 
                                     c("alpha"= "Alpha", "beta"="Beta"),
                                     selected = "alpha"))
    

    slightly hacky but does the job.

    0 讨论(0)
提交回复
热议问题