I've always understood that a Shiny conditionalPanel()
can't share the same reactive object with another conditional panel. My solution has been to build essentially the same reactive object over and over, with each reactive object tagged to each of the conditional panels. But this is cumbersome. Is there an efficient workaround, where the same reactive objective can be shared among multiple conditional panels?
There are related questions I believe in Stack Overflow but with examples that are so cumbersome they are hard to decipher. I offer here a very simple, clear example.
I present the example code below, where I commented-out the shared header for one of the conditional panels (the second panel) so that the user can conditionally render a plot or a table. If I uncomment that line in the second conditional panel, then neither plot nor table renders. Does anyone have a solution, other than my creating two header objects in this example? In the actual code this is intended for, there would be far more than two headers so you can see why I'd like to share that reactive header.
library(shiny)
DF <- data.frame(row.names = LETTERS[1:5], X = c(1:5), Y = c(6:10))
ui <- fluidPage(
selectInput("view","View options:",c("Plot","Table")),
conditionalPanel(
condition = "input.view == 'Plot'",
textOutput("header"),
plotOutput("plot")
),
conditionalPanel(
condition = "input.view == 'Table'",
# textOutput("header"),
tableOutput("table")
)
)
server <- function(input, output, session) {
output$header <-renderText({paste(input$view,"has been selected")})
output$plot <- renderPlot({plot(DF$X,DF$Y)})
output$table <- renderTable(DF)
}
shinyApp(ui, server)
Taking into account Limey's comment, it now works:
library(shiny)
DF <- data.frame(row.names = LETTERS[1:5], X = c(1:5), Y = c(6:10))
ui <- fluidPage(
selectInput("view","View options:",c("Plot","Table")),
textOutput("header"),
conditionalPanel(
condition = "input.view == 'Plot'",
plotOutput("plot")
),
conditionalPanel(
condition = "input.view == 'Table'",
tableOutput("table")
)
)
server <- function(input, output, session) {
output$header <-renderText({paste(input$view,"has been selected")})
output$plot <- renderPlot({plot(DF$X,DF$Y)})
output$table <- renderTable(DF)
}
shinyApp(ui, server)