I am quite new to shiny and I did not find a solution to do what I wanted.
My aim is to have a Previous/Next button for a select field (selectInput) which is dynamically created (I require this for future developments as the choices will change in function of the dataset).
I inspired myself from this post Add back/next button to date range input in shiny.
However I can't manage to do the same in my case.
Here is my try with a simple example (the objective is to apply this to a more complex dataset).
library(shiny)
vector_choices <- seq(5, 50, by = 5)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
uiOutput("selector"),
tags$div(class="row",
tags$div(uiOutput("prevBin")),
tags$div(uiOutput("nextBin")))
),
mainPanel(
textOutput("text"),
plotOutput("distPlot")
)
)
)
server <- function(input, output, session) {
output$selector <- renderUI({
selectInput("bins",
"Bins",
choices = as.list(vector_choices),
selected = 25)
})
output$prevBin <- renderUI({
actionButton("prevBin",
label = "Previous")
})
output$nextBin <- renderUI({
actionButton("nextBin",
label = "Next")
})
observeEvent(input$prevBin, {
current <- which(vector_choices == input$bins)
if(current > 1){
updateSelectInput(session, "bins",
choices = as.list(vector_choices),
selected = vector_choices[current - 1])
}
})
observeEvent(input$nextBin, {
current <- which(vector_choices == input$bins)
if(current < length(vector_choices)){
updateSelectInput(session, "bins",
choices = as.list(vector_choices),
selected = vector_choices[current + 1])
}
})
output$distPlot <- renderPlot({
x <- rnorm(100)
bins <- seq(min(x), max(x), length.out = as.numeric(input$bins))
hist(x, breaks = bins, col = 'darkgray', border = 'white')
})
}
shinyApp(ui = ui, server = server)
If anyone came across this problem or is a shiny expert and can point me in the right direction it will be greatly appreciated.
Thanks
EDIT: I corrected the code based on BigDataScientist's answer and I added a condition for first and last occurences of the list.
You were close.
You want to update the selectInput()
not the renderUI()
that creates the selectInput()
;)
So replace in both your updateSelectInput()
"selector"
with "bins"
:
updateSelectInput(session, "bins", choices = vector_choices,
selected = vector_choices[current - 1])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With