2016-08-04 86 views
1

下面的代碼顯示了一個帶有兩個選項卡的UI,每個選項卡都包含相同的複選框面板。如果另一個面板更新,我希望一個面板更新,反之亦然。在服務器中使用了觀察功能,但由於某種原因,如果tab1被更改,它只會更新tab2上的checkBoxGroup,但不會以其他方式更改。有沒有人有如何解決這個問題的想法?R Shiny:使用相同的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) 

回答

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) 
+1

謝謝UnnamedUser! – WhoKnows19