【问题标题】:Take action when any of the button is clicked Shiny R单击任何按钮时采取行动 Shiny R
【发布时间】:2021-09-18 10:28:46
【问题描述】:

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

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)

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

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

谢谢。

【问题讨论】:

标签: r shiny action-button


【解决方案1】:

改用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)

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      一些替代方法:

      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)
      

      【讨论】:

        猜你喜欢
        • 2022-01-15
        • 1970-01-01
        • 1970-01-01
        • 2023-03-09
        • 1970-01-01
        • 1970-01-01
        • 2021-01-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多