Search code examples
rshinylapplyobservers

How do you use lapply on two variables in a Shiny app?


I have the following chunk of code:

  observeEvent(subsettedData(), {
    lapply(col_names, function(var) {
      selections <- unique(subsettedData()[[var]])
      if (length(input[[var]]) == 0)
        updateSelectInput(session = session, inputId = var, choices = selections)
    })
  }) 

I would like to rework it to incorporate the fact that the inputId is different than the column names in the subsetted data.

Instead of the above code applying over col_names I am trying to apply it this way with 2 variables:

  observeEvent(subsettedData(), {
    lapply(col_names, col_aliases, function(cn, an) {
      selections <- unique(subsettedData()[[cn]])
      if (length(input[[cn]]) == 0)
        updateSelectInput(session, inputId = an, choices = selections)
    })
  }) 

However, it is not working.


Solution

  • I think you are looking for mapply():

    observeEvent(subsettedData(), {
        mapply(FUN = function(cn, an) {
          selections <- unique(subsettedData()[[cn]])
          if (length(input[[cn]]) == 0)
            updateSelectInput(session, inputId = an, choices = selections)
        }, cn = col_names, an = col_aliases)
      }) 
    

    (untested, because code is not reproducible,...)