1
votes

I'm trying to use a selectInput as an actionButton. I like how each time I press the actionButton, the counter adds numbers. I'm trying to achieve the same effect for selectInput.

In the example below, I demonstrate the functionality of the actionButton. I've tried to mimic it's effect with selectInput with this code.

 selectnumber <- eventReactive(input$select,
                                if (input$select == "A") {
                                             input$action + 1
  })
  

In this approach, the number updates, but it depends on the actionButton. Instead I'd like the number to update whenever I select A after I have B selected.

library(shiny)

ui <- fluidPage(
    sidebarLayout(
        sidebarPanel(
          selectInput("select", "Select Input", choices = c(" ", "A", "B")),
          actionButton("action", "Action Button")
        ),
        mainPanel(
         textOutput("out1"),
          textOutput("out2")
        )
    )
)

server <- function(input, output) {
  output$out1 <- renderText({
    paste("Action Button: ", input$action)
  })
  
#  count <- reactive({
#    input$action
# })
  
  selectnumber <- eventReactive(input$select,
                                if (input$select == "A") {
   input$action + 1
  })
  
  output$out2 <- renderText({
    paste("Select Input: ", selectnumber())
  })
}

options(shiny.autoreload = TRUE)
shinyApp(ui = ui, server = server)


Is there a better working way to make selectInput behave like actionButton?

1

1 Answers

2
votes

Here's one way using observeEvent and reactiveValues. This increments the count everytime you select 'A' in selectInput.

library(shiny)

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      selectInput("select", "Select Input", choices = c(" ", "A", "B")),
      actionButton("action", "Action Button")
    ),
    mainPanel(
      textOutput("out1"),
      textOutput("out2")
    )
  )
)

server <- function(input, output) {

  rv <- reactiveValues(count = 0)
  output$out1 <- renderText({
    paste("Action Button: ", input$action)
  })
  
  observeEvent(input$select, {
          if (input$select == "A") rv$count <- rv$count + 1
  })
  
  output$out2 <- renderText({
    paste("Select Input: ", rv$count)
  })
}

options(shiny.autoreload = TRUE)
shinyApp(ui = ui, server = server)