R, Shiny: next / previous button for selectInput

I'm brand new to brilliant and I haven't found a solution to do what I wanted.

My goal is to have a Previous / Next button for the selected field (selectInput) that is dynamically created (for this I require this for future events as the selection will change depending on the dataset).

I inspired myself for this post Add back / next button to current input range in shiny .

However, in my case, I cannot do the same.

Here is my attempt at a simple example (the goal 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 stumbled upon this issue or a brilliant expert and can point me in the right direction, it will be very helpful.

thank

EDIT: I corrected the code based on BigDataScientist's answer and added a condition for the first and last occurrence of the list.

+3


source to share


1 answer


You were close.

You want to update selectInput()

, not renderUI()

that creates selectInput()

;)



So replace in yours updateSelectInput()

"selector"

with "bins"

:

updateSelectInput(session, "bins", choices = vector_choices,
                      selected = vector_choices[current - 1])

      

+2


source







All Articles