user29609 user29609 - 2 months ago 36
R Question

Set maximum sliderInput value based on reactive output value

I have a Shiny app with a slider input and I would like to set the maximum possible value for the slider based on a maximum value in the dataset uploaded by the user. The max distance will change based on the dataset uploaded.

Here is a minimum working example of what I am trying to do. Below I just hardcode the number for the maxdistance, but in my code it is calculated:

library(shiny)

ui <- fluidPage(
sliderInput("range_one", "Core:", min = 0, max = textOutput("maxdistance"), value = c(0,0))
)

server <- function(input,output) {
output$maxdistance <- renderText({
maxdistance <- 250
return(maxdistance)
})
}

shinyApp(ui=ui,server=server)


I get the following error:

Error in max - min : non-numeric argument to binary operator


Which makes sense because I as asking for a text output, so how do I get this output as a numeric value for use in the sliderInput() function?

Answer

Here is an example.

library(shiny)

ui <- shinyUI(fluidPage(

  titlePanel("Example"),

  sidebarLayout(
    sidebarPanel(
      sliderInput("bins",
                  "Number of bins:",
                  min = 1,
                  max = 50,
                  value = 30),
      actionButton("change", "Change slider max value")
    ),

    mainPanel(
      plotOutput("distPlot")
    )
  )
))

server <- shinyServer(function(input, output, session) {

  observeEvent(input$change, {
    max = sample(50:100, 1)
    updateSliderInput(session, "bins", max=max)
  })

  output$distPlot <- renderPlot({
    x <- faithful[, 2] 
    bins <- seq(min(x), max(x), length.out = input$bins + 1)

    hist(x, breaks = bins, col = 'darkgray', border = 'white')
  })
})

shinyApp(ui = ui, server = server)
Comments