【问题标题】:In Shiny, what's the difference between req() and an if() statement?在 Shiny 中,req() 和 if() 语句有什么区别?
【发布时间】:2020-04-04 19:23:09
【问题描述】:

假设我有以下 UI:

ui <- fluidPage(
checkboxGroupInput("checkbox", "", choices = colnames(mtcars)),
tableOutput("table")
)

一旦至少选择了一个复选框选项,我想呈现mtcars 的表格。为此,我遇到了req(),但我看不出它与if 语句有什么不同,即使阅读有关此函数的文档,它的定义也非常接近if 语句的定义:

确保值是可用的(“真实”——见细节) 进行计算或动作。如果任何给定的值是 不真实,通过引发“静默”异常停止操作 (不被 Shiny 记录,也不显示在 Shiny 应用的 UI 中)。

那么,这个表格是怎么渲染的:

server <- function(input, output) {

    output$table <- renderTable({
    req(input$checkbox)
    mtcars %>% select(input$checkbox)
    })
}

shinyApp(ui, server)

和这个不同?:

server <- function(input, output) {

    output$table <- renderTable({
    if(!is.null(input$checkbox))
    mtcars %>% select(input$checkbox)
    })
}

shinyApp(ui, server)

TL;DR:req()if 语句的不同之处在于您的编写方式?

【问题讨论】:

    标签: r shiny shiny-reactivity


    【解决方案1】:

    好吧,您可以通过输入不带括号的名称来查看req 的代码。

    function (..., cancelOutput = FALSE) 
    {
        dotloop(function(item) {
            if (!isTruthy(item)) {
                if (isTRUE(cancelOutput)) {
                    cancelOutput()
                }
                else {
                    reactiveStop(class = "validation")
                }
            }
        }, ...)
        if (!missing(..1)) 
            ..1
        else invisible()
    }
    

    基本上发生的事情是,它循环遍历您传入的所有值并检查它们是否看起来“真实”,而不仅仅是检查是否为空。如果是这样,它将取消输出。而if 语句只会有条件地执行一段代码,不一定会取消输出。例如当你有这个块时

    server <- function(input, output) {
        output$table <- renderTable({
          if(!is.null(input$checkbox)) 
             mtcars %>% select(input$checkbox)
          print("ran")
        })
    }
    

    if 表达式中的代码在条件下运行,但之后的 print() 仍然始终运行,因为它不在 if 块中。但是用req

    server <- function(input, output) {
        output$table <- renderTable({
          req(input$checkbox)
          mtcars %>% select(input$checkbox)
          print("ran")
        })
    }
    

    req() 基本上会中止块的其余部分,因此如果req 不是“真实”值,print() 就不会运行。它只是更容易防止不必要的代码运行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-06
      • 2012-09-16
      • 1970-01-01
      • 2012-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多