Search code examples
rshiny

Set sliderInput values after rendering table shiny


I have built an application in Rhsiny which houses multiple applications on its own. It consists of multiple tabs and sub tabs which all have their own tools on them. Now I have one where I want to set the values of a slicer to the max value in a dataframe, but the dataframe is initially not yet renderend, therefore I struggle to set the values in the UI. I do not want to generate the table before loading the application because I have a lot of other applications and try to keep the workspace as clean as possible, i.e. if this tab is not opened I do not want to load the table/run the script at al. A small example of what I try to do;

library(shiny)
library(dplyr)

ui <- fluidPage(
  fluidPage(
    
    sidebarLayout(
      sidebarPanel(
        helpText("test"),
        
        actionButton("btn1", "Run script"),
        
        sliderInput("slider1",
                    label = "test",
                    min = 5, max = 100, value = 5)
      ),
      
      mainPanel(
        tableOutput("dt")
      )
    )
  )
)

server <- function(input, output, session) {
  observeEvent(input$btn1,{
    #source(something)
    df <- data.frame(x = 1:10, y = sample.int(100,10))
    output$dt <- renderTable({
      df %>%
        filter(y >= input$slider1)
    })
  })
}
shinyApp(ui, server)

UI

After I hit the button, normally a script sources which produces a dataframe, I would like the max value of the slicer to be the max value of y in that dataframe, but because the UI is generated before the dataframe, I struggle to do so. The outcome of the script can vary allot, therefore I would like to generate the max value in a generic way. what I have tried so far;

sliderInput("slider1",
                    label = "test",
                    min = 5, max = if(exists("df")){max(df$y)}else{1}, value = 5)

But this won't work, it gives the same error as if I would set the max value to max(df$y. So my question in general; is there a way to set the values of a UI element generically after rendering something in the server? Thank you in advance!


Solution

  • Just use updateSliderInput(). Add this inside the observeEvent of your server part:

    updateSliderInput(session, "slider1", max = max(df$y))