Reputation: 2091
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?
Upvotes: 4
Views: 3754
Reputation: 2091
Here is the code I am using on the server side to achieve the desired result of my original question, without the need for an action button:
observe({
infile <- input$file # user input file upload
if(!is.null(infile)) {
processed <- processed() # list of processed elements returned from earlier reactive({}) function with my app
processed_data <- processed$processed_data # get the processed data from the list and save as data frame
maxdistance <- max(processed_data$distance) # calculate the max distance from the processed data
updateSliderInput(session, "range_one", max=maxdistance) # update the slider called "range_one" based on the maxdistance
}
})
This allows the app to use the default maximum slider value until a file is uploaded. Once the user uploads a file, the data is processed and the slider is updated.
Upvotes: 0
Reputation: 23101
Change as follows, it will work:
sliderInput("range_one", "Core:",
min = 0, max = as.integer(textOutput("maxdistance")),
value = c(0,0))
Upvotes: 1
Reputation: 12087
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)
Upvotes: 4