Shiny 中 select 单选按钮的活动选项卡

Active tab to select radio button in Shiny

我有以下 Shiny 应用程序代码,用户可以在其中 select 单选按钮,然后激活相应的选项卡面板。

我的问题是如何做相反的事情,即如果用户 select 是一个选项卡面板,您如何激活相应的单选按钮。

下面是一个可重现的例子。

如果您select Tab 2 单选按钮,例如,Tab 2 被激活

如果您随后 select 选项卡 3,则选项卡 2 单选按钮保持 selected,我希望它更新为选项卡 3 单选按钮

谢谢

library(shiny)

radio_button_choices = list("Tab 1" = 1, "Tab 2" = 2, "Tab 3" = 3)

ui <- fluidPage(

sidebarLayout(
    sidebarPanel(
      radioButtons(inputId = "radio_button", label = h5("Select tab"), choices = radio_button_choices)),

    mainPanel(
      tabsetPanel(id = "tab",

                  tabPanel("Tab1", value = "panel1", htmlOutput("text1")),
                  tabPanel("Tab2", value = "panel2", htmlOutput("text2")),
                  tabPanel("Tab3", value = "panel3", htmlOutput("text3"))
      )
    ) 
  )
)

server <- function(input, output, session) {

  observeEvent(input$radio_button, {
    updateTabsetPanel(session, "tab",
                      selected = paste0("panel", input$radio_button)
    )
  })

  output$text1 = renderUI({
    str1 = "This is tab 1"
    HTML(paste(str1)) 
  })

  output$text2 = renderUI({
    str1 = "This is tab 2"
    HTML(paste(str1)) 
  })

  output$text3 = renderUI({
    str1 = "This is tab 3"
    HTML(paste(str1)) 
  })

}

# Run the application 
shinyApp(ui = ui, server = server)

你可以用 updateRadioButtons 做类似的事情。

您的 tabPanel 选择可能也喜欢类似的向量。

library(shiny)

radio_button_choices = list("Tab 1" = 1, "Tab 2" = 2, "Tab 3" = 3)
panel_choices = list("Panel 1" = 1, "Panel 2" = 2, "Panel 3" = 3)

ui <- fluidPage(

  sidebarLayout(
    sidebarPanel(
      radioButtons(inputId = "radio_button", label = h5("Select tab"), choices = radio_button_choices)),

    mainPanel(
      tabsetPanel(id = "tab",

                  tabPanel(names(panel_choices)[1], value = panel_choices[[1]], htmlOutput("text1")),
                  tabPanel(names(panel_choices)[2], value = panel_choices[[2]], htmlOutput("text2")),
                  tabPanel(names(panel_choices)[3], value = panel_choices[[3]], htmlOutput("text3"))
      )
    ) 
  )
)

server <- function(input, output, session) {

  observeEvent(input$radio_button, {
    updateTabsetPanel(session, "tab", selected = input$radio_button)
  })

  output$text1 = renderUI({
    str1 = "This is tab 1"
    HTML(paste(str1)) 
  })

  output$text2 = renderUI({
    str1 = "This is tab 2"
    HTML(paste(str1)) 
  })

  output$text3 = renderUI({
    str1 = "This is tab 3"
    HTML(paste(str1)) 
  })

  observeEvent(input$tab, {
    updateRadioButtons(session, "radio_button", selected = input$tab)
  })

}

# Run the application 
shinyApp(ui = ui, server = server)