首页 文章

用变量显示Shiny中的进度条

提问于
浏览
1

我正在玩Shiny中的进度条 . 对于我正在开发的实际Shiny应用程序即时抓取推文 . 并且 - 因为这需要很长时间 - 我想通过进度条通知用户 . 我做了一个小的可重现的例子,概述了我的问题:

library(shiny)

ui <- fluidPage(
  actionButton("show", "Show modal dialog")
)

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

  test_function <- function(city){
    return(city)
  }

  observeEvent(input$show, {
    withProgress(message = 'Making plot', value = 0, {
      cities <- c("Amsterdam", "London", "Paris", "Toronto")
      counter = 1

      for (city in length(cities)) {
        progress = counter / length(cities)
        city <- test_function(city)
        incProgress(progress, detail = paste("Scraping city: ", city))
        Sys.sleep(1)
        counter = counter + 1
      }
    })
  })

}

shinyApp(ui, server)

我正在寻找的是一个进度条 - 每秒 - 显示另一个城市:

“刮阿姆斯特丹”“刮劫伦敦”

等等...

进度条应根据城市填写(伦敦是2/4 - > 50%) . 但是当我运行上面的代码时,我只得到“刮城4” .

有关我应该做的调整的任何想法,以获得我想要的结果?

2 回答

  • 1

    我相信这就是你所追求的:

    library(shiny)
    
    ui <- fluidPage(
      actionButton("show", "Show modal dialog")
    )
    
    server <- function(input, output, session) {
    
      test_function <- function(city){
        return(city)
      }
    
      observeEvent(input$show, {
        withProgress(message = 'Making plot', value = 0, {
          cities <- c("Amsterdam", "London", "Paris", "Toronto")
    
          for (i in 1:length(cities)) {
            progress = (i-1) / length(cities)
            city <- test_function(cities[i])
            incProgress(progress, detail = paste("Scraping city: ", city))
            Sys.sleep(1)
          }
        })
      })
    
    }
    shinyApp(ui, server)
    

    主要问题是 for (city in length(cities)) ,因为 length(cities) 返回4因此只显示了第四个城市 .

    此外,计数器应从0(i-1)开始 . 因为当它从1开始时,进度条会立即跳到25%并在最后一个城市开始时结束 .

    对许多城市来说并不是什么大不了的事,但只有4个,这是非常明显的 .

    服务器也可以是这样的:

    server <- function(input, output, session) {
    
      test_function <- function(city){
        return(city)
      }
    
      observeEvent(input$show, {
        withProgress(message = 'Making plot', value = 0, {
          cities <- c("Amsterdam", "London", "Paris", "Toronto")
          counter = 0
    
          for (i in cities) {
            progress = counter / length(cities)
            city <- test_function(i)
            incProgress(progress, detail = paste("Scraping city: ", city))
            Sys.sleep(1)
            counter = counter + 1
          }
        })
      })
    
    }
    
  • 1

    如果你想要一个更漂亮的进度条,请查看 shinyWidgets 包:

    library(shiny)
    library(shinyWidgets)
    
    ui <- fluidPage(
      column(4,progressBar(id = "pb4", value = 0, display_pct = T)),
      actionButton("show", "Show modal dialog")
    
    )
    server <- function(input, output, session) {
      observeEvent(input$show, {
        for (i in 1:10) {
          updateProgressBar(session = session, id = "pb4", value = i*10)
          Sys.sleep(0.5)
        }
      })
    }
    
    shinyApp(ui, server)
    

    enter image description here

相关问题