MPhD
MPhD

Reputation: 456

updateSelectInput with shiny within and Rmarkdown document

I am trying to use Shiny inline within an Rmarkdown document. In this simple example, I want to create 3 inputs: the first allows you to choose one or more of 4 countries ("GHA","RWA","TZA","UGA"). In the real app, I want the landscapes options to update based on the actual landscapes available in the selected countries. However, in this example, I just want the initial view (when "GHA" is selected by default) to be "L01" to "L06". Then, if any changes are made to the "countries" input, the landscape options would change to ("hmm","hum"). I have read that in some cases observe vs reactive options might be preferred and have tried a variety of variations, but essentially any time I include an updateSelectInput command I lose any options for landscapes in the app. Thanks for any insights!

library(shiny)   
  selectInput("countries", 'Country',
                list("GHA","RWA","TZA","UGA"),
                multiple=TRUE, 
                selectize=TRUE, 
                selected="GHA")
  checkboxGroupInput("landscapes", label=("Landscape"), 
                choices=c("L01","L02","L03","L04","L05","L06"), selected="L01")   
  radioButtons("checkPlot", label = ("Factors"), 
                         choices=c("Gender of Household Head", "Water Source(s)"),
                         selected = "Water Source(s)")
  observeEvent(input$countries, {
    updateSelectInput(session, "landscapes", choices=c("hmm","hum"))   })

Upvotes: 1

Views: 760

Answers (1)

Mal_a
Mal_a

Reputation: 3760

Here is example code which is solving your issue:

library(shiny)
library(DT)
shinyApp(
  ui = fluidPage(
    selectInput("countries", 'Country',
                list("GHA","RWA","TZA","UGA"),
                multiple=TRUE, 
                selectize=TRUE, 
                selected="GHA"),
    uiOutput("checkbox")
  ),
  server = function(input, output) {

    output$checkbox <- renderUI({
      choice <-  if(any(input$countries == "GHA")){
        choice <- c("L01","L02","L03","L04","L05","L06")
      }else{ 
        choice <- c("hmm","hum")}
      checkboxGroupInput("landscapes", label=("Landscape"), choices = choice, selected = choice[1])

    })

   }
)

I have not used updateSelectInput because in this case i think if...else... statement works better. In details the code says that if any of the selection (as you set multiple = TRUE in the selectInput) is equal to GHA then it gives choices from L01 to L02, if it is not equal to GHA then choices are hmm and hum.

** Just for complitness if you use the updateSelectInput or observeEvent etc. it should be placed in the server not in the ui.

Upvotes: 2

Related Questions