R shiny sliderInput with restricted range

后端 未结 2 1475
情书的邮戳
情书的邮戳 2020-12-10 21:12

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

相关标签:
2条回答
  • 2020-12-10 21:50

    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))
    
    0 讨论(0)
  • 2020-12-10 21:59

    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)
    

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

    0 讨论(0)
提交回复
热议问题