首页 > 解决方案 > R闪亮:在完成所有observeEvent代码之前更新tabsetpanel

问题描述

我想立即更新 tabsetpanel,而不是等到完成下载功能。在这里你可以找到一个简单的代码它有一个按钮,当它按下时,它模拟下载,并更新一个tabsetpanel。我想在完成下载之前更新面板。

谢谢!

server <- function(input, output,session) {

observeEvent(input$goPlot,{

updateTabsetPanel(session, "inTabset",
                  selected = 'Summary'
)

output$plot <- renderPlot({
  input$goPlot # Re-run when button is clicked

  # Create 0-row data frame which will be used to store data
  dat <- data.frame(x = numeric(0), y = numeric(0))

  withProgress(message = 'Making plot', value = 0, {
    # Number of times we'll go through the loop
    n <- 10

    for (i in 1:n) {
      # Each time through the loop, add another row of data. This is
      # a stand-in for a long-running computation.
      dat <- rbind(dat, data.frame(x = rnorm(1), y = rnorm(1)))

      # Increment the progress bar, and update the detail text.
      incProgress(1/n, detail = paste("Doing part", i))

      # Pause for 0.1 seconds to simulate a long computation.
      Sys.sleep(1)
    }
  })

  plot(dat$x, dat$y)
})



})
}

ui <- shinyUI(fluidPage(
actionButton('goPlot', 'Go plot'),
tabsetPanel(id = "inTabset",
tabPanel("Plot", plotOutput("plot")),
tabPanel("Summary")

)
)   

)

shinyApp(ui = ui, server = server)

标签: rshiny

解决方案


Shiny 仅在更新所有无效的观察或反应语句后更新 UI。因此,当您想要这样的工作流程时,您必须构建反应链。我通过在单独的响应式语句中提取数据准备来解决了这个问题(这并不是真正必要的,但总是一个好主意),然后我将绘图移动到摘要选项卡。我想切换标签的原因是为了看情节。如果这不正确,请纠正我。但这会推迟计算,直到显示选项卡。goPlot现在为了防止在单击按钮之前开始计算,我刚刚添加了该行

req(input$goPlot) 

到反应式语句的开头。

server <- function(input, output,session) {
  observeEvent(input$goPlot,{

    updateTabsetPanel(session, "inTabset",
                      selected = 'Summary'
    )
    generate_plot <- reactive({

      req(input$goPlot) 

      # Create 0-row data frame which will be used to store data
      dat <- data.frame(x = numeric(0), y = numeric(0))

      withProgress(message = 'Making plot', value = 0, {
        # Number of times we'll go through the loop
        n <- 10

        for (i in 1:n) {
          # Each time through the loop, add another row of data. This is
          # a stand-in for a long-running computation.
          dat <- rbind(dat, data.frame(x = rnorm(1), y = rnorm(1)))

          # Increment the progress bar, and update the detail text.
          incProgress(1/n, detail = paste("Doing part", i))

          # Pause for 0.1 seconds to simulate a long computation.
          Sys.sleep(1)
        }
      })

      plot(dat$x, dat$y)

    })
    output$plot <- renderPlot({
      generate_plot()
    })



  })
}

ui <- shinyUI(fluidPage(
  actionButton('goPlot', 'Go plot'),
  tabsetPanel(id = "inTabset",
              tabPanel("Plot"),
              tabPanel("Summary", plotOutput("plot"))

  )
)   

)

shinyApp(ui = ui, server = server)

希望这可以帮助!!


推荐阅读