9

I try to make two mutually dependent input sliders in a shiny app but don't seem to get it to work. I plan to use this kind of situation in a shiny app and for ease illustrate it here with a simplified 'glass half empty / full' example in which one slider should show glass fullness and one emptyness:

library(shiny)

ui =(pageWithSidebar(
  headerPanel("Glass fullness"),
  sidebarPanel(
    sliderInput("Full", "% water", min = 0, max = 1, value = 0.2),
    #display dynamic UI
    uiOutput("Empty")),
  mainPanel()
))

server = function(input, output, session){

  # make dynamic slider 
  output$Empty <- renderUI({
    sliderInput("Empty", "% air", min=0, max=1, value=1-input$Full)
  })

}

runApp(list(ui = ui, server = server))

I understand the value = 0.2 and value=1-input$Full cause above code only to make the second slider dependent on the first but not the other way around. My problem is that I want to make both dependent on each other. I tried adding an uiOutput("Full") & dynamic slider for Full but did not manage to work around circular coding.

The result of above code looks as follows:

Glass half empty/full screenshot

Any help greatly appreciated!

2 Answers 2

8

Hi define your sliders in the UI and updated them in the server when it's needed :

library(shiny)

ui =pageWithSidebar(
  headerPanel("Glass fullness"),
  sidebarPanel(
    sliderInput(inputId = "Full", label = "% water", min = 0, max = 1, value = 0.2),
    sliderInput(inputId = "Empty", label = "% air", min = 0, max = 1, value = 1 - 0.2),
    uiOutput("Empty")),
  mainPanel()
)

server = function(input, output, session){

  # when water change, update air
  observeEvent(input$Full,  {
    updateSliderInput(session = session, inputId = "Empty", value = 1 - input$Full)
  })

  # when air change, update water
  observeEvent(input$Empty,  {
    updateSliderInput(session = session, inputId = "Full", value = 1 - input$Empty)
  })

}

shinyApp(ui = ui, server = server)
0

It is because in the second slider you have:

sliderInput("Empty", "% air", min=0, max=1, value=1-input$Full)

where value is 1-input$Full therefore it does depend on the first one, but in the first slider value is 0.2:

sliderInput("Full", "% water", min = 0, max = 1, value = 0.2),

and due to this 0.2, there is no relation with the second one.

Although, as you mention, you will end up with circular dependency.

1
  • Thanks Leo, I edited the question to make it more clear that I understand these parts of the code lead to only one slider being dependent on the other. I try to find out how to make them mutually dependent.
    – adrbart
    Dec 20, 2016 at 17:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.