R Shiny Handling - error handling from empty data frames

I am writing my first Shiny app and still enjoy it. My application works with a data frame that includes many variables that measure nutritional aspects. It allows the user to select ranges from half a dozen continuous variables using sliders. These inputs are used for a subset of the data frame, then created ggplotbased on the subset of data.

My problem is this: when the selected ranges result in missing data in the frame of the data subset, I get this red error message printed on the main panel, where the graph will usually be:

Error: argument is of length zero (from: Error in if (nrow(layer_data) == 0) return() : argument is of length zero).  

I understand why this error occurs, and it makes sense if I get static graphs during a typical data analysis session. However, I am trying to find the right way to handle this in a brilliant web application situation.

Since this message does not make sense to the user, I would like to:

1) You can instead replace it with a reasonable message OR
2) Return an empty graph OR
3) Do not show anything (i.e. an error message or graph to the user when the data frame is empty)

The problem is that if I check an empty data frame and return another (empty) graph or message, then when the user changes the settings of the slider to what has data, the correct graph does not appear (since the reactive object is no longer the same). If I just show the error message as it is now, and the user changes the settings, the graph will update accordingly.

Can someone recommend a way to handle this gracefully in Shiny?

+4
source share
1 answer

shiny 0.10.0 , , need validate. groups cohort. , need . CSS , :

library(shiny)
library(ggplot2)
myData <- data.frame(group = sample(letters[1:4], 100, TRUE)
                     , cohort = sample(0:4, 100, TRUE)
                     , value = runif(100))
runApp(
  list(ui = fluidPage(
    column(4,
    checkboxGroupInput('group', 'Pick a group', choices = letters[1:4]),
    selectizeInput('cohort', 'Pick a cohort', choices = 0:4)),
    column(8, plotOutput('myplot'))
  )
  , server = function(input, output, session) {
    appData <- reactive({
      myData[myData$group %in% input$group & myData$cohort == input$cohort,]
    })
    output$myplot <- renderPlot({
      validate(
        need(input$group, 'Please select at least one group'),
        need(input$cohort > 0, 'Please choose a cohort greater than zero')
      )
      g <-ggplot(appData(),aes(x=group, y=value)) +
        stat_summary(fun.y=sum, geom="bar") +
        ggtitle(paste('cohort', input$cohort))
      g
    })
  }
  )
)

enter image description here

+5

Source: https://habr.com/ru/post/1536287/


All Articles