3

Situation: I have one input where you can choose "small" or "big", a csv-file with data and another input, where you can choose from a list from the csv depending on your choice of "small" or "big".

Problem: I cannot find a way to access the variable input$selecter in the updateSelectizeInput function.

Here is my minimal code example which unfortunately does not work:

library(shiny)

ui=fluidPage(
  selectInput('selecter', "Choose ONE Item", choices = c("small","big")),
    selectizeInput('chooser', 'Choose SEVERAL Items', choices = NULL, multiple = TRUE)
)

server=function(input,output,session){
 DatafromMytable=read.csv("mytable.csv", header=TRUE, sep=";")
 # mysubset=subset(DatafromMytable,Size=="big") #
   mysubset=subset(DatafromMytable,Size==input$selecter)
 updateSelectizeInput(session, "chooser", choices = mysubset$Item) 

}

shinyApp(ui, server)

Question: What do I need to change in the line updateSelectizeInput(session, "chooser", choices = mysubset$Item) to make the code work?

nexonvantec
  • 572
  • 1
  • 5
  • 18

2 Answers2

3

You have to make your variable mysubset into a reactive, and then call its value with mysubset(). Also, you need an observer that fires the updateSelectizeInput whenever it sees that mysubset() has changed.

Example below. Note that I have commented out your read.csv statement, and added some sample data to make your example reproducible. Hope this helps!

library(shiny)

ui=fluidPage(
  selectInput('selecter', "Choose ONE Item", choices = c("small","big")),
  selectizeInput('chooser', 'Choose SEVERAL Items', choices = NULL, multiple = TRUE)
)

server=function(input,output,session){

  #DatafromMytable=read.csv("mytable.csv", header=TRUE, sep=";")
  DatafromMytable=data.frame(Size=c('small','small','big','big'),Item=c(1,2,3,4))

  mysubset= reactive ({
    subset(DatafromMytable,Size==input$selecter)
    })

  observeEvent( mysubset(),{
  updateSelectizeInput(session, "chooser", choices = mysubset()$Item) 
  })

}

shinyApp(ui, server)
Florian
  • 24,425
  • 4
  • 49
  • 80
1

The simplest solution seems to be to just wrap the two lines that have reactive variables with observe({ ... }).

 observe({  
 mysubset=subset(DatafromMytable,Size==input$selecter)
 updateSelectizeInput(session, "chooser", choices = mysubset$Item) 
 })
nexonvantec
  • 572
  • 1
  • 5
  • 18
  • 1
    If you do not need the contents of the subsetted dataframe anywhere else, this is actually a very simple and elegant solution! +1 – Florian Jan 17 '18 at 09:00