单击任何按钮时执行操作 Shiny R

Take action when any of the button is clicked Shiny R

如何观察多个按钮中的任意一个被点击?例如,我们有三个按钮,我想在单击任何按钮时显示通知。这是一个示例代码

library(shiny)


ui <- fluidPage(
  actionButton('button1', 'button1'),actionButton('button2', 'button2'),actionButton('button3', 'button3'))

server <- function(input, output, session) {
  
  
  
  
  
  observe({
    
    req(input$button1, input$button2, input$button3)
    
    
    showNotification("This is a notification.")
    
    
    
  })
}

shinyApp(ui, server)

上面的代码并不令人满意,因为在启动页面时,只有当三个按钮都被点击时,才会显示通知。

另外,是否可以知道点击了哪个按钮?

谢谢。

改用observeEvent并将所有触发器放在c()

library(shiny)


ui <- fluidPage(
    actionButton('button1', 'button1'),actionButton('button2', 'button2'),actionButton('button3', 'button3'))
server <- function(input, output, session) {
    observeEvent(c(input$button1, input$button2, input$button3), ignoreInit = TRUE, {
        showNotification("This is a notification.")
    })
}

shinyApp(ui, server)

input 转换为列表并将其用作 observeEvent 的触发器对象:

observeEvent(reactiveValuesToList(input),{
  #do something
})

一些替代方法:

library(shiny)
library(purrr)

ui <- fluidPage(
  actionButton('button1', 'button1'),actionButton('button2', 'button2'),actionButton('button3', 'button3'))

server <- function(input, output, session) {
  
  paste0('button', 1:3) %>% 
  map(~ observeEvent(input[[.x]], {
    showNotification("This is the general notification.")
    showNotification(paste(.x, 'pressed'))
  }))
  
  
}

shinyApp(ui, server)

或仅使用 observe():

library(shiny)
library(stringr)
library(purrr)

ui <- fluidPage(
  actionButton('button1', 'button1'),actionButton('button2', 'button2'),actionButton('button3', 'button3'))

server <- function(input, output, session) {
  observe({
    nms <- str_subset(names(input), 'button')
    if ( any(map_lgl(nms,~ input[[.x]] != 0)) ) {
      
      showNotification("This is a notification.")
      
    } 
  })
}

shinyApp(ui, server)