我正在构建一个包含多个选项卡的应用程序,其中一些涉及过多的计算,另一些涉及快速计算.允许用户在反应性或手动更新之间进行选择的复选框与"刷新"按钮相结合将是理想的.
下面的简单示例说明了我的目标.它几乎可以工作,除了在"自动刷新" - 检查框未选中时最后一次刷新,这是一个痛苦,如果计算密集的选项卡打开.有没有办法解决?
ui.r
library(shiny)
shinyUI(fluidPage(
titlePanel("Test"),
sidebarLayout(
sidebarPanel(
checkboxInput("autoRefresh", "Automatically refresh", TRUE),
actionButton("refresh", "Refresh!"),
radioButtons("choice", "Choice of value:",
c("10" = 10,
"20" = 20))
),
mainPanel(
tabsetPanel(type = "tabs",
tabPanel("Add random decimals to value", textOutput("value"))
)
)
)
))
Run Code Online (Sandbox Code Playgroud)
server.r
library(shiny)
shinyServer(function(input, output) {
output$value <- renderText({
input$refresh
if(input$autoRefresh == 1) {
input$choice
}
isolate({
output <- runif(1,0,1) + as.numeric(input$choice)
})
})
})
Run Code Online (Sandbox Code Playgroud)
提前谢谢了!
在此解决方案中,我创建了两个观察者:一个用于观察refresh按钮何时被按下,第二个用于何时choice发生更改。第一个总是更新输出。
第二个检查 的状态input$autoRefresh,然后退出或更新renderText.
不幸的是,您必须将runif命令写入两次,这可能不利于更新代码(如果您执行两次操作,则更容易引入错误)。在实践中,您可能想要创建一个新函数,然后如果这是实际应用程序中的复杂/多行过程,则只需调用该函数即可。
shinyServer(function(input, output) {
observe({
input$refresh
output$value<-renderText({
isolate(runif(1,0,1) + as.numeric(input$choice))
})
})
observe({
input$choice
output$value<-if(input$autoRefresh==0) return() else {
renderText({isolate(runif(1,0,1) + as.numeric(input$choice))})
}
})
})
Run Code Online (Sandbox Code Playgroud)