Charl Francois Marais
Charl Francois Marais

Reputation: 345

Shiny R determine which checkbox was ticked

I would like to know which checkbox group was clicked. For example, when clicking on group "a"; "b" then I want to store in a variable that it came from "subset_one".

Any ideas?

library(shiny)
  obs_ev <- "c(input[['subset_one']], 
               input[['subset_two']], 
               input[['subset_three']])"
  shinyApp(
    shinyUI(
      fluidPage(
        uiOutput('ui')
      )
    ),
    shinyServer(function(session, input, output) {

      output$ui <- renderUI({
        inputPanel(
          checkboxGroupInput('subset_one',   'Subset:', choices = c("a", "b")),
          checkboxGroupInput('subset_two',   'Subset:', choices = c("c", "d")),
          checkboxGroupInput('subset_three', 'Subset:', choices = c("e", "f"))
        )
      })

      observeEvent(eval(parse(text = obs_ev)), {
        print("1")
        print(input[['subset_one']])
        print("2")
        print(input[['subset_two']])
        print("3")
        print(input[['subset_three']])

        dat  <- eval(parse(text = obs_ev))

        print(dat)

      }, ignoreNULL = FALSE)
    })
  )

Upvotes: 0

Views: 353

Answers (1)

MrFlick
MrFlick

Reputation: 206197

If you want to know what was triggered, I think you're better off setting up different observers for each object you want to watch, and then set up a function that can handle all the responses outside of the actual observer. For example, consider this solution

library(shiny)
obs_list <- c("subset_one","subset_two","subset_three")
shinyApp(
  shinyUI(
    fluidPage(
      uiOutput('ui')
    )
  ),
  shinyServer(function(session, input, output) {

    output$ui <- renderUI({
      inputPanel(
        checkboxGroupInput('subset_one',   'Subset:', choices = c("a", "b")),
        checkboxGroupInput('subset_two',   'Subset:', choices = c("c", "d")),
        checkboxGroupInput('subset_three', 'Subset:', choices = c("e", "f"))
      )
    })

    lapply(obs_list, function(obs) {
      observeEvent(input[[obs]], {changeVal(obs, input[[obs]])}, ignoreNULL = FALSE)
    })

    changeVal <- function(obj, val) {
      print(paste("changed", obj, "val", paste(val, collapse=",")))
      dat  <- do.call("c", lapply(obs_list, function(x) input[[x]]))

      print(dat)
    }

  })
)

Note that I got rid of the eval(parse()) stuff. I try to avoid that when possible. But here we use lappy to build a different observer for each input. We then call a function to handle the response, indicating which object was actually clicked.

Upvotes: 2

Related Questions