Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R shiny sliderInput with restricted range

Tags:

r

shiny

In my R shiny sliderInput I want to restrict the range of the input of a given slider with larger maximum value. For example assume the input has to be in the interval [1:10].

Of course I could now define min=1, max= 10 in sliderInput options, but then I will get only a slider with values in this interval.

My goal is to see a slider with values (for example) in [1:50], but the user can move this slider only in the interval [1:10]. This would make my app even better. Is this possible?

like image 925
R_FF92 Avatar asked Jul 14 '16 14:07

R_FF92


2 Answers

Building up from your previous question you can use the min values, here slider 1 is restricted to 80 max and slider 2 restricted to 50

rm(list = ls())
library(shiny)

slider1limit <- 80
slider2limit <- 50

ui <-pageWithSidebar(

  # Application title
  headerPanel("Sliders should sum to 100!"),
  # Sidebar with sliders whos sum should be constrained to be 100
  sidebarPanel(
    sliderInput("slider1", "Slider 1: ", min = 0, max = 100, value = 0, step=1),
    uiOutput("slider")),

  # Create table output
  mainPanel(tableOutput("restable"))
)

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

  observeEvent(input$slider2,{
    values <- min((100 - input$slider2),slider1limit)
    updateSliderInput(session, "slider1", min =0,max=100, value = values)
  })
  output$slider <- renderUI({
    values <- min((100 - input$slider1),slider2limit)
    sliderInput("slider2", "Slider 2: ", min=0,max=100, value = values)
  })

  output$restable <- renderTable({
    myvals<- c(input$slider1, input$slider2, 100-input$slider1-input$slider2)
    data.frame(Names=c("Slider 1", "Slider 2", "Slider 3"),Values=myvals)
  })
}
runApp(list(ui = ui, server = server))
like image 97
Pork Chop Avatar answered Nov 12 '22 00:11

Pork Chop


You can use the from-min and from-max data attributes. This requires to modify the sliderInput function.

sliderInput2 <- function(inputId, label, min, max, value, step=NULL, from_min, from_max){
  x <- sliderInput(inputId, label, min, max, value, step)
  x$children[[2]]$attribs <- c(x$children[[2]]$attribs, 
                               "data-from-min" = from_min, 
                               "data-from-max" = from_max, 
                               "data-from-shadow" = TRUE)
  x
}

ui <- fluidPage(
  sliderInput2("slider", "Slide:",
              min = 0, max = 100, value = 50, step = 5, from_min = 20, from_max = 80
  )
)

server <- function(input, output) {}

shinyApp(ui, server)

enter image description here

And thanks to the from-shadow data attribute, there is a segment showing the available range.

like image 45
Stéphane Laurent Avatar answered Nov 12 '22 00:11

Stéphane Laurent