[英]R Shiny: How to start and stop an iteration / animation using action buttons
在 R Shiny 中,我想創建一個 animation 由一個動作按鈕啟動,並且可以被另一個動作按鈕中斷。 以下是無效代碼的虛擬版本。 目標是開始迭代,每秒打印 year=year+1 直到達到最大值。 然而,用戶也應該能夠使用停止按鈕中斷該過程。
例如,我使用observeEvent()、observe() 和reactiveValues() 構造而不是for 循環的原因是我無法停止由開始按鈕啟動的循環。
在這個例子中,既不啟動也不停止 function 工作。 使用 for 循環,我開始迭代,但停止按鈕僅在迭代結束時“停止”該過程。 在 for 循環中使用observeEvent(input$stop, { break })
的構造不起作用。 我猜原因是,該事件僅在執行 for 循環后才被觀察到,因為在此之前之前的進程仍然處於活動狀態。
shinyApp(
ui=fluidPage(
actionButton("start", "Start"),
actionButton("stop", "Stop"),
actionButton("reset", "Reset"),
verbatimTextOutput("text")
),
server=function(input, output, session) {
r <- reactiveValues(animation = FALSE, year=2000)
observeEvent(input$start, {
r$animation <- TRUE
})
observeEvent(input$stop, {
r$animation <- FALSE
})
observeEvent(input$reset, {
r$animation <- FALSE
r$year <- 2000
})
observe({
if(isTRUE(r$animation)) {
r$year <- r$year + 1
Sys.sleep(1)
if(r$year==2005) {
r$animation <- FALSE
r$year <- 2000
}
}
})
output$text <- renderText({ paste0("It is year ", r$year) })
})
這個方法與您的非功能示例代碼有點偏離,但是我想知道您是否知道sliderInput
的 animation 功能。
我認為這可能會節省您編寫大量自定義代碼:
library(shiny)
ui <- fluidPage(
titlePanel("Animation Slider Test"),
sidebarLayout(
sidebarPanel(
sliderInput(
inputId = "animation_slider",
label = "Animation Slider",
min = 2000L,
max = 2020L,
value = 2000L,
step = 1L,
round = FALSE,
ticks = TRUE,
animate = animationOptions(
interval = 1000,
loop = FALSE,
playButton = actionButton("play", "Play", icon = icon("play"), width = "100px", style = "margin-top: 10px"),
pauseButton = actionButton("pause", "Pause", icon = icon("pause"), width = "100px", style = "margin-top: 10px")
),
width = NULL,
sep = "",
pre = "Year: ",
post = NULL,
timeFormat = NULL,
timezone = NULL,
dragRange = TRUE
),
actionButton("reset", "Reset", icon = icon("rotate-left"), width = "100px", style = "margin-top: -87px")
),
mainPanel(
verbatimTextOutput("text")
)
)
)
server <- function(input, output, session) {
observeEvent(input$reset, {
updateSliderInput(
session = session,
inputId = "animation_slider",
label = NULL,
value = 2000L,
min = NULL,
max = NULL,
step = NULL,
timeFormat = NULL,
timezone = NULL
)
})
output$text <- renderText({ paste("It is year", input$animation_slider) })
}
shinyApp(ui, server)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.