了解为什么 Shiny 中的操作按钮在使用多个操作按钮时不起作用

时间:2021-01-11 16:53:33

标签: r shiny shinydashboard shinyapps flexdashboard

为什么当我将 Shiny 手册 (https://shiny.rstudio.com/articles/action-buttons.html) 中的几个操作按钮代码放在一起时,它不运行(即没有按钮反应)?每个代码分别运行良好。如何解决? (这与这篇文章有关:Convert Shiny App R code to Rmarkdown Shiny App code: with observeEvent and eventReactive

# Code from https://shiny.rstudio.com/articles/action-buttons.html

library(shiny)

ui <- fluidPage(
  # Pattern 1 - Command
  tags$head(tags$script(src = "message-handler.js")),
  actionButton("do", "Click Me"),
  hr(),

  # Pattern 2 - Delay reactions
  actionButton("go", "Go"),
  numericInput("n", "n", 50),
  plotOutput("plot2"), 
  hr(),

  # Pattern 4 - Reset buttons
  actionButton("runif", "Uniform"),
  actionButton("reset", "Clear"),
  plotOutput("plot4")
  
)

server <- function(input, output, session) {
  
  # Pattern 1 - Command
  observeEvent(input$do, {
    session$sendCustomMessage(type = 'testmessage',
                              message = 'Thank you for clicking')
  })

  # Pattern 2 - Delay reactions
  randomVals <- eventReactive(input$go, {
    runif(input$n)
  })
  output$plot2 <- renderPlot({
    hist(randomVals())
  })
  
  # Pattern 4 - Reset buttons
  v <- reactiveValues(data = NULL)
  observeEvent(input$runif, {
    v$data <- runif(100)
  })
  observeEvent(input$reset, {
    v$data <- NULL
  })
  output$plot4 <- renderPlot({
    if (is.null(v$data)) return()
    hist(v$data)
  })
}

shinyApp(ui, server)

更新:

在最初的问题中,我在模式 2 和 4 示例中有 output$plot。现在这些已被替换为 output$plot2output$plot4 - 这部分解决了问题。 - 模式 2 和 4 的按钮现在可以使用了。但是,模式 1 仍然不起作用。

1 个答案:

答案 0 :(得分:0)

正如建议的那样,您不能有两个具有相同 ID 的输出。试试这个

library(shiny)

ui <- fluidPage(
  # Pattern 1 - Command
  #tags$head(tags$script(src = "message-handler.js")),
  actionButton("do", "Click Me"),
  hr(),
  
  # Pattern 2 - Delay reactions
  actionButton("go", "Go"),
  numericInput("n", "n", 50),
  #plotOutput("plot"), 
  #hr(),
  
  # Pattern 4 - Reset buttons
  actionButton("runif", "Uniform"),
  actionButton("reset", "Clear"),
  plotOutput("plot")
  
)

server <- function(input, output, session) {
  
  # Pattern 1 - Command
  observeEvent(input$do, {
    # session$sendCustomMessage(type = 'testmessage',
    #                           message = 'Thank you for clicking')
    print('Thank you for clicking')
  })
  
  ### Pattern 2 - Delay reactions
  randomVals <- eventReactive(input$go, {
    runif(input$n)
  })
  
  ### Pattern 4 - Reset buttons
  v <- reactiveValues(data = NULL)
  observeEvent(input$runif, {
    v$data <- runif(100)
  })
  observeEvent(input$go, {
    v$data <- runif(input$n)
  })
  observeEvent(input$reset, {
    v$data <- NULL
  })
  output$plot <- renderPlot({
    if (is.null(v$data)) {
      return()
    }else {
      hist(v$data)
    }

  })
}

shinyApp(ui, server)
相关问题