3

I have a Shiny web app with numerous plots. Each plot has its own SQL Query to get data. It is possible to that one of the queries returns a table with insufficient data. If that happens, then I want to display a text message in the tab where the plot would be.

server.R:

library(shiny)
library(RMySQL)

shinyServer(function(input, output, session) {

    output$lineGraphOne <- renderPlot({

        table <- getDataSomeHowOne()

        if(dim(table[1]) < 3) {            
            error <- paste("Some error message")            
        } else {            
            plot(x = as.Date(table$date), y = table$count)            
        }
    })

    output$lineGraphTwo <- renderPlot({

        table <- getDataSomeHowTwo()

        if(dim(table[1]) < 3) {            
            error <- paste("Some error message")            
        } else {            
            plot(x = as.Date(table$date), y = table$count)            
        }

    })    
})

ui.R

library(shiny)

shinyUI(navbarPage("Title",                   
    tabPanel("Name",                            
        sidebarLayout(            
            mainPanel(
                tabsetPanel(id = "tabs",
                    tabPanel("One", plotOutput("lineGraphOne")),
                    tabPanel("Two", plotOutput("lineGraphTwo"))
                )
            ),            
            sidebarPanel(
                dateInput('queryDate', 'Datum:', value = as.Date("2010-04-09"))
            )
        )            
    )                   
))

How would I achieve displaying the error string instead of the plot in the corresponding tab?

micstr
  • 5,080
  • 8
  • 48
  • 76
arkhon
  • 765
  • 2
  • 11
  • 28

1 Answers1

7

Have a look at validate, note that the example is taken from Write error messages for your UI with validate

rm(list = ls())
library(shiny)
runApp(list(
  ui = (fluidPage(

    titlePanel("Validation App"),

    sidebarLayout(
      sidebarPanel(
        selectInput("data", label = "Data set",
                    choices = c("", "mtcars", "faithful", "iris"))
      ),

      # Show a plot of the generated distribution
      mainPanel(
        tableOutput("table"),
        plotOutput("plot")
      )
    )
  )),
  server = function(input, output) {

    data <- reactive({ 
      validate(
        need(input$data != "", "Please select a data set")
      )
      get(input$data, 'package:datasets') 
    })

    output$plot <- renderPlot({
      hist(data()[, 1], col = 'forestgreen', border = 'white')
    })

    output$table <- renderTable({
      head(data())
    })

  }
))
Pork Chop
  • 28,528
  • 5
  • 63
  • 77