【发布时间】:2019-11-30 03:31:57
【问题描述】:
下面的应用程序包含一个 selectInput 和两个选项 iris 和 mtcars 以及一个显示当前选择的标题。
- 如果用户选择
iris,则在标题下方呈现相应数据集的DT。 - 如果用户选择
mtcars,则标题下方不会呈现任何内容。
这是截图:
我将选定的数据集存储在反应式表达式sel_df 中。该表达式在返回相应的数据集之前检查用户是否使用req(input$dataset=='iris') 选择了虹膜:
sel_df = reactive({
req(input$dataset=='iris')
iris
})
sel_df 被传递给renderDT,它呈现数据表:
output$df = renderDT({
sel_df()
})
然后,我使用 h3 标头、数据表和数据表的标签呈现一些 UI 以显示 selectInput 的当前值:
output$tbl = renderUI({
tagList(
h3(paste0('Selected:', input$dataset)), # Header should be visible regardless of the value of input$dataset
tags$label(class = 'control-label', style = if(!isTruthy(isolate(sel_df()))) 'display:none;', `for` = 'df', 'Data:'), # Label should only show if input$dataset == 'iris'
DTOutput('df')
)
})
我希望数据表及其标签仅在 sel_df 输出数据集时可见。但是由于应用程序的结构方式,这需要output$tbl(上面的renderUI)依赖于sel_df,以便每当input$dataset == 'mtcars' 时整个UI 块都会消失。
我想要的输出要求output$tbl 仅依赖于input$dataset,因此无论input$dataset 的值如何,h3 标头始终可见。为此,我尝试使用isolate '隔离'sel_df,但output$tbl 在每次失效时仍会调用sel_df。
我不确定我哪里出错了。我想我可能错误地使用了isolate,但我不知道为什么,我想知道是否有人可以解释一下。
这是完整的应用程序:
library(shiny)
library(DT)
ui <- fluidPage(
selectInput('dataset', 'Dataset', c('iris', 'mtcars')),
uiOutput('tbl')
)
server <- function(input, output, session) {
sel_df = reactive({
req(input$dataset=='iris')
iris
})
output$df = renderDT({
sel_df()
})
output$tbl = renderUI({
tagList(
h3(paste0('Selected:', input$dataset)), # Header should be visible regardless of the value of input$dataset
tags$label(class = 'control-label', style = if(!isTruthy(isolate(sel_df()))) 'display:none;', `for` = 'df', 'Data:'), # Label should only show if input$dataset == 'iris'
DTOutput('df')
)
})
}
shinyApp(ui, server)
【问题讨论】:
-
" 但 output$tbl 在每次失效时仍会调用 sel_df。"您如何跟踪它,...使用显示模式 = 展示?
-
我只是根据
output$tbl在input$dataset != "iris"完全消失这一事实中推断出来的,这意味着output$tbl在调用sel_df时会停止。
标签: r shiny reactive-programming