如何使用两个不同的 actionButton 触发相同的情节但不在 shinyapp 中重复整个功能?

How to trigger the same plot with two different actionButton but not repeating the whole function in shinyapp?

我想在实际 运行 应用程序之前有一个供用户使用的示例,就像我在下面的代码中添加了一个 runexample 按钮一样。但是对于这个按钮,我不想写一个重复的代码来实现与另一个按钮相同的功能。有什么好的方法吗?


library(shiny)

# Define UI for application that draws a histogram
ui <- fluidPage(
   
   # Application title
   titlePanel("Old Faithful Geyser Data"),
   
   # Sidebar with a slider input for number of bins 
   sidebarLayout(
      sidebarPanel(
         sliderInput("bins",
                     "Number of bins:",
                     min = 1,
                     max = 50,
                     value = 30),
         actionButton("run","run"),
         actionButton("runExample","runExample")
         ),
   
      # Show a plot of the generated distribution
      mainPanel(
       
         plotOutput("distPlot")
      )
   )
)

# Define server logic required to draw a histogram
server <- function(input, output) {
   
  plot <- eventReactive(input$run,{
    x    <- faithful[, 2] 
    bins <- seq(min(x), max(x), length.out = input$bins + 1)
    hist(x, breaks = bins, col = 'darkgray', border = 'white')
  })
 
   output$distPlot <- renderPlot({
     plot()
      
   })
   
}

# Run the application 
shinyApp(ui = ui, server = server)

这样的东西行得通吗?

勾选documentation (duelling buttons)。 我直接在 observeEvent 函数中将 runExample 案例的 bins 值设置为默认值 30,但您可以在其他地方定义此值。

ui <- fluidPage(
  
  # Application title
  titlePanel("Old Faithful Geyser Data"),
  
  # Sidebar with a slider input for number of bins 
  sidebarLayout(
    sidebarPanel(
      sliderInput("bins",
                  "Number of bins:",
                  min = 1,
                  max = 50,
                  value = 30),
      actionButton("run","run"),
      actionButton("runExample","runExample")
    ),
    
    # Show a plot of the generated distribution
    mainPanel(
      
      plotOutput("distPlot")
    )
  )
)

# Define server logic required to draw a histogram
server <- function(input, output) {
  
  x    <- faithful[, 2] 
  v <- reactiveValues(data = NULL)
  
  observeEvent(input$run, {
      v$bins <- seq(min(x), max(x), length.out = input$bins + 1)
  })
  
  observeEvent(input$runExample, {
    v$bins <- seq(min(x), max(x), length.out = 30 + 1)
  }) 
  

  output$distPlot <- renderPlot({
    hist(x, breaks = v$bins, col = 'darkgray', border = 'white')
    
  })
  
}

# Run the application 
shinyApp(ui = ui, server = server)