Limit the two sliders. In the gloss line, add up to 100

I want to create a brilliant application with two slides that add up to 100. This means that if the user changes the value of one slider, the other slider automatically changes to fulfill the constraint (100-input $ slider1).

I found a similar question here: Code example

with the following code:

Server:

library(shiny)

# Define server logic required
shinyServer(function(input, output) {

  output$slider2 <- reactiveUI(function() {
    sliderInput("slider2", "Slider 2", min = 0,  max = 100 - input$slider1, value = 0)  
  })

  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)
  })
})

interface:

library(shiny)

# Define UI for application
shinyUI(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("slider2")
  ),

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

This is already a solution, which is in order. But here you can only change the slider 1 to automatically change the slider 2. On the other hand, if the user changes the slider 2, then slider 1 does not fit the limit. How can I make this possible so that both sliders can be changed so that the other meets the constraints?

+1
1

updateSliderInput renderUI

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

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) {

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

  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))

enter image description here

+3

Source: https://habr.com/ru/post/1619048/


All Articles