I've been struggling with this all day and I've kind of solved it (horrible hack). However there experience is not smooth and displays side-effects.
What I want is three sliders with a range of 0 to 100 constrained such that their sum should always be 100.
This is a screenshot of what it looks like
Here's the server.R shiny code.
library(shiny)
oldState<-NULL
newState<-NULL
getState<-function(input) c(input$slider1, input$slider2, input$slider3)
# Define server logic required
shinyServer(function(input, output, session) {
observe({
newState<<-getState(input)
i<-which(oldState-newState != 0)[1]
if(!is.na(i)){
rem <- 100-newState[i]
a<-sum(newState[-i])
if(a==0) newState[-i]<<-rem/length(newState[-i])
else newState[-i]<<-rem*(newState[-i]/a)
for(j in 1:length(newState))
if(j!=i)
updateSliderInput(session, paste0("slider", j), value=newState[j])
}
oldState<<-newState
})
output$restable <- renderTable({
myvals<-getState(input)
myvals<-c(myvals, sum(myvals))
data.frame(Names=c("Slider 1", "Slider 2", "Slider 3", "Sum"),
Values=myvals)
})
})
and here is the ui.R shiny code
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 = 40, step=1),
sliderInput("slider2", "Slider 2: ", min = 0, max = 100, value = 30, step=1),
sliderInput("slider3", "Slider 3: ", min = 0, max = 100, value = 30, step=1)
),
# Create table output
mainPanel(
tableOutput("restable")
)
))
Now this does pretty much what it should except two things:
- It feels like a hack i.e. there should be a better way of doing this
- When I move a slider into a position it sometimes jumps to a slightly lower or higher position. I have no idea why.
How do I fix these two issues?
See Question&Answers more detail:
os