我有以下Shiny应用程序代码,用户可以在其中选择单选按钮,然后激活相应的选项卡面板。
我的问题是如何反向操作,即如果用户选择选项卡面板,如何激活相应的单选按钮。
下面是可复制的示例。
例如,如果选择选项卡2单选按钮,则选项卡2被激活
如果您随后选择选项卡3,则选项卡2单选按钮保持选中状态,我希望它更新为选项卡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)