R Shiny:两次使用相同的checkBoxGroup

时间:2016-08-04 09:49:38

标签: r checkbox shiny

下面的代码显示了一个带有两个选项卡的UI,每个选项卡都包含相同的复选框面板。如果另一个面板更新,我希望更新一个面板,反之亦然。在服务器中使用observe函数,但由于某种原因,如果tab1被更改,它只更新tab2上的checkBoxGroup,而不是相反。有没有人有关于如何解决这个问题的想法?

   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)

1 个答案:

答案 0 :(得分:2)

你不应该有两个具有相同id的小部件。而不是仅仅调用它们,比如variable1variable2,并创建两个不同的观察者来更新复选框。

    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)