How to use capture and use only the variables from the active tab in R Shiny?

30 Views Asked by At

How to use the same variable name across different tabs to store different values?

Here is a workable code.


require(shiny)
require(shinydashboard)


# Define the UI
ui <- dashboardPage(
  # Title of the app
  dashboardHeader(title = "Shiny App"),
  # Navigation panel
  dashboardSidebar(
    sidebarMenu(
      menuItem("Home", tabName = "home", icon = icon("home")),
      menuItem("Tab 1", tabName = "tab1", icon = icon("circle-nodes")),
      menuItem("Tab 2", tabName = "tab2", icon = icon("circle-nodes"))
    )
  ),
  
  dashboardBody(
    tabItems(
      tabItem(tabName = "tab1", 
              fluidRow( 
                column(selectInput(inputId = "disease",
                                   label = "Disease",
                                   choices = c(
                                     "Breast Cancer" = "BreastCancer",
                                     "Kidney Cancer" = "KidneyCancer",
                                     "Skin Cancer" = "SkinCancer")
                ),
                textOutput({
                  "output_text_tab1"
                }),
                width = 6)
              ) # End of fluidRow
      ), # End of tab 1
      tabItem(tabName = "tab2", 
              fluidRow(
                column(selectInput(inputId = "disease",
                                   label = "Disease",
                                   choices = c(
                                     "Breast Cancer" = "BreastCancer",
                                     "Kidney Cancer" = "KidneyCancer",
                                     "Skin Cancer" = "SkinCancer")
                ),
                textOutput({
                  "output_text_tab2"
                }),
                width = 6)
              ) # End of fluidRow
      ) # End of tab 2
    ) # end of tabItems
  ) # end of dashboardBody
) # end of dashboardPage



# Define server logic to plot  ----
server <- function(input, output, session){
  output$output_text_tab1 <- renderText({ paste0("Tab1 Disease: ", input$disease) })
  output$output_text_tab2 <- renderText({ paste0("Tab2 Disease: ", input$disease) })
  
}

# Call the app
shinyApp(ui = ui, server = server)

Here, the variable disease is used in both tab1 and tab2. When I use the drop-down from tab1 and print the value, it prints correctly. However, when I move to tab2 and try to reselect the disease, it still prints the value selected previously in tab1.

One way to solve this would be to define separate names. But while dealing with long codes, this might be not feasible.

How to use capture and use variables from the active tab? Is it possible to use a separate server function for each tab such that only the variable defined within that tab will be used?

0

There are 0 best solutions below