gpt4 book ai didi

R Shiny - 隔离使用 req() 检查先决条件的响应式(Reactive)表达式

转载 作者:行者123 更新时间:2023-12-02 00:51:36 25 4
gpt4 key购买 nike

下面的应用程序包含一个 selectInput 和两个选项 irismtcars 以及一个显示当前选择的标题。

  • 如果用户选择 iris,相应数据集的 DT 将呈现在标题下方。
  • 如果用户选择 mtcars,标题下方不会呈现任何内容。

截图如下:

enter image description here

我将选定的数据集存储在响应式(Reactive)表达式 sel_df 中。该表达式在返回相应的数据集之前检查用户是否使用 req(input$dataset=='iris') 选择了鸢尾花:

sel_df = reactive({

req(input$dataset=='iris')

iris
})

sel_df 被传递给 renderDT 来呈现数据表:

output$df = renderDT({

sel_df()

})

然后我渲染一些 UI 以使用 h3 header 、数据表和数据表标签显示 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 block 就会消失。

我想要的输出要求 output$tbl 仅依赖于 input$dataset,这样无论 的值如何,h3 header 始终可见输入$数据集。为此,我尝试使用 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 依赖于 input$dataset,所以每次 input$dataset 的值改变时自然会调用它。 sel_df() 也依赖于 input$dataset 并在它发生变化时被调用。这就是预期的样子,我不认为你的标签被调用,因为它取决于 sel_df()

但是请注意,当sel_df 为NULL 时,taglist() 调用也将返回NULL。这是因为当 input$dataset != "iris" 时,您的 sel_df() 调用失败,因此 tagList 也失败了:

If any of the given values is not truthy, the operation is stopped by raising a "silent" exception (not logged by Shiny, nor displayed in the Shiny app's UI).

试试这个:

server <- function(input, output, session) {
sel_df = reactive({
if(input$dataset=='iris') {
iris
} else {
NULL
}
})

您会发现,使用 mtcars 时,h3() 标签会显示,但标签会根据需要隐藏。

关于R Shiny - 隔离使用 req() 检查先决条件的响应式(Reactive)表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57141237/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com