为什么当我将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$plot2
和output$plot4
-这部分解决了问题。-模式2和模式4的按钮现在可以使用。但是,模式%1仍然不起作用。
按照建议,您不能有两个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)