0

I have a shiny application which takes an input of a csv file.

I have a plotting function in server.R

myPlot <- function(data){This function uses the variables from the data frame in parenthesis. This data frame is the input from the uploaded file.}

Imagine if the data frame does not have the columns which are used by the function we will encounter an error in the shiny tab.

How does one handle such an error?

I would like to handle it by throwing a message stating "the following file is not compatible."

Cyrus Mohammadian
  • 4,982
  • 6
  • 33
  • 62
radhika
  • 77
  • 1
  • 7
  • 2
    You can use `validate()` and `need()`: http://shiny.rstudio.com/articles/req.html – Michal Majka Sep 10 '16 at 17:31
  • wont work as validate and need will check inputs but in this case we need to apply the uploaded file to the plotting function. – radhika Sep 10 '16 at 19:57
  • tryCatch(myplot(ss),error = function(e){print("Did it")},warning = function(e){print("Did it")}) Did the following works for most errors. However it does not handle facet_wrap getting Error in layout_base(data, vars, drop = drop) : At least one layer must contain all variables used for facetting How do I handle this? Need a robust error handler for plots – radhika Sep 10 '16 at 20:45

1 Answers1

0

It is just as @UnnamedUser suggested, you can use the validate() and need() functions to check conditions:

Example: I am trying to plot data$Col_A and data$Col_B. The plot only renders if both columns are in the data.frame, otherwise it shows a predefined error message.

library(shiny)

data <- data.frame(
  Col_A = 1:5,
  Col_D = 16:20)

ui <- fluidPage(
  plotOutput("plot")
)

server <- function(input, output, session){
  output$plot <- renderPlot({
    validate(
      need(
        sum(c("Col_A", "Col_B") %in% colnames(data)) == 2, "Col_A and/or Col_B columns are missing!")
    )
    plot(data$Col_A, data$Col_B)
  })
}

shinyApp(ui, server)
GyD
  • 3,902
  • 2
  • 18
  • 28