Home > database >  Set an Output Component to Empty in R/Shiny
Set an Output Component to Empty in R/Shiny

Time:10-29

I have uiOutput and plotOutput components in my main Shiny panel.

plotOutput("plot_data"), 
uiOutput("summary_data")

I have the typical code in the server function to react and populate each component, for example:

  output$plot_data <- renderPlot({
    hist(data_vars())
    })
    
  output$summary_data <- renderPrint({
    summary(data_vars())
    }) 

I'd like to add functionality to each that sets the output component of the other to NULL or an empty string, etc. so that these two outputs share the same space. When one has data, the other is empty. I don't think it would work this way, but it could look like this:

  output$plot_data <- renderPlot({
    # Code to "flatten" uiOutput

    # Then populate the component    
    hist(data_vars())
    })
    
  output$summary_data <- renderPrint({
    # Code to "flatten" plotOutput
    
    # Then populate the component
    summary(data_vars())
    }) 

I think this might be done using observeEvent, but I haven't found a way to completely remove content from one so that the other could take up the same space on the page. Please help. Thank you.

CodePudding user response:

Rather than having a separate plotOutput and printOutput, you can have just one uiOutput and then you can add code in the server to show which output you would like in that slot. Here's a working example where I added a button to swap between views.

library(shiny)

ui <- fluidPage(
  actionButton("swap","Swap"),
  uiOutput("showPart")
)

server <- function(input, output, session) {
  showState <- reactiveVal(TRUE)
  observeEvent(input$swap, {showState(!showState())})
  
  output$plot_data <- renderPlot({
    hist(mtcars$mpg)
  })
  
  output$summary_data <- renderPrint({
    summary(mtcars)
  })

  output$showPart <- renderUI({
    if (showState()) {
      plotOutput("plot_data")
    } else {
      verbatimTextOutput("summary_data")    
    }
  })
}

shinyApp(ui, server)

Using this method only one of the two output will be rendered in the uiOutput slot.

  • Related