Defining a specific range of values for a sliderInput in Shiny

Viewed 637

Even thought there are many topics dealing with the properties of the sliderInput in Shiny, I couldn't find a solution to what I'm trying to do.

My problem is simple: I would like to adapt my code (see below) in order to create a slider with an interval of "10" (from 0 to 10, 10 to 20, 3 to 13 etc...)

###running example: 

ui <-basicPage(
  sliderInput("id", "Ranking",
                           min = 2, max = 60, value = c(2,15)))


server <- server <- function(input, output) {}

shinyApp(ui, server)

Any ideas please ?

2 Answers

You can call updateSliderInput every time the slider is changed, to enforce the interval.

The trick here is to remember previous value to update the right handler (the one that that didn't change)

INTERVAL = 13
value = c(2, 2 + INTERVAL)

ui <-basicPage(
  sliderInput("id", "Ranking",
              min = 2, max = 60, value = value))

server <- server <- function(input, output, session) {
  observeEvent(input$id,{
    newvalue = input$id
    
    if(value[1] != newvalue[1] && newvalue[2] - newvalue[1] != INTERVAL)
      updateSliderInput(session, "id", value = c(newvalue[1], newvalue[1] + INTERVAL))
    
    if(value[2] != newvalue[2] && newvalue[2] - newvalue[1] != INTERVAL)
      updateSliderInput(session, "id", value = c(newvalue[2] - INTERVAL, newvalue[2]))
    
    value <<- newvalue
  })
}

shinyApp(ui, server)

You may want the step argument inside your sliderInput() function. Documentation here. But I was having issues with that having to be able to slide to individuals numbers.

Or you could select a single input as the starting range, and add 10 to that number.

library(shiny)


ui <- fluidPage(
    sliderInput("num2", "Pick a starting Range", value = 20, min = 2, max = 60),
    textOutput("num2")
)

server <- function(input, output, session) {
    output$num2 <- renderText({
        paste0("Your range is ", input$num2, " to ", input$num2 +10, "!")
    })
}

# Run the application 
shinyApp(ui = ui, server = server)

enter image description here

Related