There is a third solution taking advantage of the fact that each button keeps the number of time is has been pressed. If you could monitor that number of time, then any change in that number will indicate which button was pressed.
Here is a short implementation. The page has three buttons (with arbitrary names):
page <- shinyUI(basicPage(
actionButton("firstbtn",label="Btn1"),
actionButton("secondbtn",label="Btn2"),
actionButton("thirdbtn",label="Btn3"),
textOutput("result")
))
shinyServer <- function(input, output, session) {
# the number of clicks on each button is zero at first
oldBtnClicks <- rep(0,3)
observeEvent({ obs <<- list(input$firstbtn, input$secondbtn, input$thirdbtn) }, ({
# store all button state in a list
BtnState <- obs
# extract in a vector the number of clicks from each
newBtnClicks <- rep(0,3)
for (i in 1:3)
newBtnClicks[i] <- if (is.null(BtnState[[i]])) 0 else BtnState[[i]][1]
# look for the change in the number of clicks
buttonClicked <- match(1, newBtnClicks - oldBtnClicks)
# show the button number that was clicked
output$result <- renderText(expr = buttonClicked)
# update hte number of clicks in the shinyServer environment
oldBtnClicks <<- newBtnClicks
}))
}
shinyApp(ui = page, server = shinyServer)
The server function first set 0 to each button's click (they have not been pressed yet). Then it sets and observer which looks for any of the button. The list being observed could be of arbitrary length.
When an event occurs, the button states are retrieved in a list (the same as the observed list). From that list, the first elements of each sublist is retrieved (this is the number of clicks on that particular button); if some buttons can be hidden (as was the case in my own application), the list of click is null and the number of click is therefore set to 0 manually.
Finally, by taking the difference between the former state and the new state, the only place which is not zero (found with match
) is the position of the button pressed. Once done, don't forget to update the button state list. Et voilà!
If your buttons have a regular name (e.g., BtnX, with X going from 1 to n), then there might be a way to built the observed list programmatically rather than by manually enumerating the buttons?