title: R Shiny: nested observe functions
body: <p>For the sample data set <code>mtcars</code>, we want to use <code>"cyl","am","carb","gear"</code> to be the candidate filters(selectInput widgets). Users should be able to select the filter they want. </p>
  
  <p>And for each filter picked, there is an '(un)select all' button associated with it. </p>
  
  <p>My issue is, since the number of filters is not fixed, so the loop statement to generate the <code>observeEvent</code> statements has to be in another <code>observe</code> function.</p>
  
  <p>Please run the following reproducible code. </p>
  
  <p>Any suggestions to make the '(un)select all' botton work? thanks.</p>
  
  <pre><code>library(ggplot2)
  library(shiny)
  server &lt;- function(input, output, session) {
    R = mtcars[,c("cyl","am","carb","gear")]
  
    output$FILTERS = renderUI({
      selectInput("filters","Filters",choices = names(R),multiple = TRUE)
    })
  
    #this observe generates filters(selectInput widgets) dynamically, not important
    observe({
      req(input$filters)
      filter_names = input$filters
  
      # count how many filters I selected
      n = length(filter_names)     
  
      # to render n selectInput    
      lapply(1:n,function(x){
        output[[paste0("FILTER_",x)]] = renderUI({
          req(input$filters)
          div(
            selectInput(paste0("filter_",x),
                        paste0(filter_names[x]),
                        choices = unique(R[,filter_names[x]]),
                        multiple = TRUE,
                        selected = unique(R[,filter_names[x]])
                        ),
            actionButton(paste0("filter_all_",x),"(Un)Select All")
          )
        })
      })
  
      # this renders all the selectInput widgets
      output$FILTER_GROUP = renderUI({
        lapply(1:n, function(i){
          uiOutput(paste0("FILTER_",i))
        })
      })
    })
  ####################   issue begins ##################### 
    observe(
  
    n = length(input$filters)
  
    lapply(
      1:n,
      FUN = function(i){
        Filter = paste0("filter_",i)
        botton = paste0("filter_all_",i)
  
        observeEvent(botton,{
          NAME = input$filters[i]
          choices = unique(mtcars[,NAME])
  
          if (is.null(input[[Filter]])) {
  
            updateCheckboxGroupInput(
              session = session, inputId = Filter, selected = as.character(choices)
            )
          } else {
            updateCheckboxGroupInput(
              session = session, inputId = Filter, selected = ""
            )
          }
        })
      }
    )
    )
  ####################   issue ends #####################
  })
  
  ui &lt;- fluidPage(
    uiOutput("FILTERS"),
    hr(),
    uiOutput("FILTER_GROUP")
  )
  
  shinyApp(ui = ui, server = server)
  </code></pre>