rshinyshinydashboardnumeric-input

Set a default value in shiny inputs (in case the user deletes it in the UI)


I am trying to set a default (or fallback) value for numericInput() in my shiny app to prevent NAs.

I am aware that the NA can be dealt with later in the server.r, but was wondering if there is a more elegant way of replacing the value within the input whenever a user deletes it in the ui.


Solution

  • The best way is to use the validate package with need() (see this SO thread), but here is something simpler and closer to what you are asking for:

    library(shiny)
    
    ui <- fluidPage(
      numericInput("obs", "Observations:", 10, min = 1, max = 100),
      verbatimTextOutput("value")
    )
    
    server <- function(input, session, output) {
      
      dafault_val <- 0
      
      observe({
        if (!is.numeric(input$obs)) {
          updateNumericInput(session, "obs", value = dafault_val)
        }
      })
      
      output$value <- renderText({ input$obs })
    }
    
    shinyApp(ui, server)