我正在玩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”。
对于我想要得到我想要的结果的调整有任何想法吗?
答案 0 :(得分: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 :(得分: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)