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

703 Views Asked by At

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.

2

There are 2 best solutions below

4
Claudiu Papasteri On BEST ANSWER

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)
0
ismirsehregal On

I'd recommend using library(shinyvalidate), which is RStudios "official" way to solve this:

library(shiny)
library(shinyvalidate)

ui <- fluidPage(
  numericInput(
    inputId = "myNumber",
    label = "My number",
    value = 0,
    min = 0,
    max = 10
  ),
  textOutput("myText")
)

server <- function(input, output, session) {
  iv <- InputValidator$new()
  iv$add_rule("myNumber", sv_required(message = "Number must be provided"))
  iv$add_rule("myNumber", sv_gte(0))
  iv$add_rule("myNumber", sv_lte(10))
  iv$enable()
  
  output$myText <- renderText({
    req(iv$is_valid())
    input$myNumber
  })
  
}

shinyApp(ui, server)