WhoKnows19 WhoKnows19 - 3 months ago 11
R Question

R Shiny: Use same checkBoxGroup twice

The code below shows a UI with two tabs with each containing the same checkbox panel. I would like one panel to update if the other is updated and vice versa. In the server the observe function is used but for some reason it only updates the checkBoxGroup on tab2 if tab1 is changed but not the other way around. Does anyone have ideas on how to solve this?

library(shiny)

ui <- shinyUI(
navbarPage("tabs",
tabPanel("tab1",
fluidPage(
sidebarPanel(
checkboxGroupInput("variable", "variable:",list("1" = "1","2" = "2","3" = "3","4" = "4","5" = "5"), selected = list("1"="1"))
)
)),
tabPanel("tab2",
fluidPage(
sidebarPanel(
checkboxGroupInput("variable", "variable:",list("1" = "1","2" = "2","3" = "3","4" = "4","5" = "5"), selected = list("1"="1"))
)
)
)
)
)

server <- function(input, output, session) {
observe({
updateCheckboxGroupInput("variable","variable:",list("1" = "1","2" = "2","3" = "3","4" = "4","5" = "5"),selected=input$variable)
})

}

shinyApp(ui = ui, server = server)

Answer

You shouldn't have two widgets with the same id. Instead of that just call them, say, variable1 and variable2 and create two distinct observers that are going to update the checkboxes.

    library(shiny)

ui <- shinyUI(
  navbarPage("tabs",           
             tabPanel("tab1", 
                      fluidPage(
                        sidebarPanel(
                          checkboxGroupInput("variable1", "variable:",
                                             list("1" = "1","2" = "2","3" = "3","4" = "4","5" = "5"), 
                                             selected = list("1"="1"))
                        )
                      )),
             tabPanel("tab2", 
                      fluidPage( 
                        sidebarPanel(
                          checkboxGroupInput("variable2", "variable:",
                                             list("1" = "1","2" = "2","3" = "3","4" = "4","5" = "5"), 
                                             selected = list("1"="1"))
                        )
                      )
             )
  )
)

server <- function(input, output, session) {
  observe({
    # added 'session'
    updateCheckboxGroupInput(session, "variable1", 
                             choices = list("1" = "1","2" = "2","3" = "3","4" = "4","5" = "5"),
                             selected = input$variable2)
  })

  observe({
    updateCheckboxGroupInput(session, "variable2", 
                             choices = list("1" = "1","2" = "2","3" = "3","4" = "4","5" = "5"),
                             selected = input$variable1)
  })

}

shinyApp(ui = ui, server = server)
Comments