3
votes

I have a basic shiny app that evaluates A + B:

library(shiny)

ui <- fluidPage(
    numericInput(inputId = "A", label = "A", value = 5, step = 1),
    sliderInput(inputId = "B", label = "B", min = 0, max = 10, value = 5),
    textOutput(outputId = "value")
)

server <- function(input, output) {
    output$value <- renderText(paste0("A + B = ", input$A + input$B))
}

shinyApp(ui = ui, server = server)

A is a numericInput value and B is a sliderInput value.

I want to constrain my app so that the maximum input value for B is always 2 * A. I, therefore, must change the hardcoded max = in sliderInput to something that can be dynamic. How can I accomplish this?

Thanks

2
All of this information is on Shinys tutorial page already, besides there are loads of similar questions already asked on SO, just make sure you do your research, as it doesn't bring anything new to the community - Pork Chop

2 Answers

11
votes

You can call updateSliderInput to change the maximum value for B from within an observe which will be triggered whenever A changes:

library(shiny)

ui <- fluidPage(
  numericInput(inputId = "A", label = "A", value = 5, step = 1),
  sliderInput(inputId = "B", label = "B", min = 0, max = 10, value = 5),
  textOutput(outputId = "value")
)

# Notice the session argument to be passed to updateSliderInput
server <- function(input, output, session) {
  output$value <- renderText(paste0("A + B = ", input$A + input$B))
  observe(updateSliderInput(session, "B", max = input$A*2))
}

shinyApp(ui = ui, server = server)
5
votes

You are looking for renderUI()

library(shiny)

ui <- fluidPage(
  numericInput(inputId = "A", label = "A", value = 5, step = 1),
  uiOutput("slider"),
  textOutput(outputId = "value")
)

server <- function(input, output) {
  output$value <- renderText(paste0("A + B = ", input$A + input$B))
  output$slider <- renderUI({
    sliderInput(inputId = "B", label = "B", min = 0, max = 2*input$A, value = 5)
  })
}

shinyApp(ui = ui, server = server)