I am trying to write Shiny App that would update slider input maximum value dynamically once I am executing arbitrary code when pressing the button:
library(shiny)
ui <- fluidPage(
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
sliderInput("bins",
"Number of bins:",
min = 1,
max = 50,
value = 30),
actionButton(inputId ="refresh", label = 'boom')
),
# Show a plot of the generated distribution
mainPanel(
plotOutput("distPlot")
)
)
)
# Define server logic required to draw a histogram
server <- function(input, output, session) {
counter <- reactiveValues(c = nrow(faithful))
observeEvent(input$refresh, {
faithful <- faithful[-1:-10, ]
counter$c <- nrow(faithful)
updateSliderInput(session, "bins", min = 1, max = counter$c, value = counter/2)
})
output$distPlot <- renderPlot({
# generate bins based on input$bins from ui.R
x <- faithful[, 2]
bins <- seq(min(x), max(x), length.out = input$bins + 1)
# draw the histogram with the specified number of bins
hist(x, breaks = bins, col = 'darkgray', border = 'white')
})
}
# Run the application
shinyApp(ui = ui, server = server)
Unfortunately, slider input update works only once! Documentation example suggests to use observe() construct watching some reactive values however I would expect that such functionality should also be working when using observeEvent() What could be wrong here?
Appreciate your help!
The problem here is not the updateSliderInput
, it is that counter
is not a reactive so it is not persitent inside the app. Just convert it to a reactive like in this example and it works fine.
library(shiny)
ui <- fluidPage(
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
sliderInput("bins",
"Number of bins:",
min = 1,
max = 50,
value = 30),
actionButton(inputId ="refresh", label = 'boom')
),
# Show a plot of the generated distribution
mainPanel(
plotOutput("distPlot")
)
)
)
# Define server logic required to draw a histogram
server <- function(input, output, session) {
counter <- reactiveValues(c = 10)
observeEvent(input$refresh, {
counter$c <- counter$c + 10
updateSliderInput(session, "bins", min = 1, max = counter$c, value = counter$c/2)
})
output$distPlot <- renderPlot({
# generate bins based on input$bins from ui.R
x <- faithful[, 2]
bins <- seq(min(x), max(x), length.out = input$bins + 1)
# draw the histogram with the specified number of bins
hist(x, breaks = bins, col = 'darkgray', border = 'white')
})
}
# Run the application
shinyApp(ui = ui, server = server)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.