You are correct that you want a validate statement. Here is a link with descriptions from the RStudio team. This will allow you to have a more informative error message. Your complete downloadHandler function would look something like the following. Note that this assumes your dataset could be null.
output$Download <- downloadHandler(
filename = function() {
paste("test.png",sep="")
},
content = function(file) {
myData <- follow_view_func()
validate(
need(!is.null(myData), "Please select valid dataset")
)
r <- rChart_line_plot(myData,log_scale = input$checkbox_log_scale_plot,isRel = input$checkboxRelativeTab2)
r$save(file, standalone = TRUE)
}
)
Here is a complete reproducible example with the iris dataset.
library(shiny)
library(rCharts)
runApp(
list(
ui = pageWithSidebar(
headerPanel("Using 'validate' for useful error messages"),
sidebarPanel(
selectInput("dataset", "Choose a dataset:",
choices = c("null", "iris")),
selectInput(inputId = "x",
label = "Choose X",
choices = c('SepalLength', 'SepalWidth', 'PetalLength', 'PetalWidth'),
selected = "SepalLength"),
selectInput(inputId = "y",
label = "Choose Y",
choices = c('SepalLength', 'SepalWidth', 'PetalLength', 'PetalWidth'),
selected = "SepalWidth"),
downloadButton("Download")
),
mainPanel(
showOutput("myChart", "polycharts")
)
),
server = function(input, output) {
datasetInput <- reactive({
switch(input$dataset,
"iris" = iris,
"null" = NULL)
})
myChart <- reactive({
myData <- datasetInput()
validate(
need(!is.null(myData), "Please select valid dataset")
)
names(myData) = gsub("\\.", "", names(myData))
p1 <- rPlot(input$x, input$y, data = myData, color = "Species",
facet = "Species", type = 'point')
p1$addParams(dom = 'myChart')
return(p1)
})
output$myChart <- renderChart({myChart()})
output$Download <- downloadHandler(
filename = function() {
paste("test.png",sep="")
},
content = function(file) {
p1 <- myChart()
p1$save(file, standalone = TRUE)
}
)
}
)
)
UPDATE
As per the OP request, it may be ideal to have no error whatsoever with the download button. The only solution I could come up with is to make the button a conditionalPanel. This intuitively makes sense to me because why would you download if there is nothing on the screen? The only change in the code above needed for this is to change:
downloadButton("Download")
to
conditionalPanel("output.myChart", downloadButton("Download"))
Now the download button will only be present when a valid chart is created.
ui.Randserver.Rfiles? - nrussell