问题
Why when I put together several action button codes from Shiny manual (https://shiny.rstudio.com/articles/action-buttons.html), it DOES NOT run (i.e. no button reacts) ? Each code separately runs fine. How to fix it? (This is relates to this post: 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)
UPDATE:
In the original question I had output$plot
in patterns 2 and 4 examples. Now these have been replaced to output$plot2
and output$plot4
- This partially resolved the problem. - Buttons for patterns 2 and 4 work now. However, Pattern 1 is still NOT working.
回答1:
As suggested you cannot have two outputs with same ID. Try this
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)
来源:https://stackoverflow.com/questions/65671195/understanding-why-action-buttons-in-shiny-dont-work-when-using-several-of-them