在闪亮,什么';req()和if()语句之间的区别是什么?

在闪亮,什么';req()和if()语句之间的区别是什么?,r,shiny,shiny-reactivity,R,Shiny,Shiny Reactivity,假设我有以下UI: ui <- fluidPage( checkboxGroupInput("checkbox", "", choices = colnames(mtcars)), tableOutput("table") ) 和这个不一样吗 server <- function(input, output) { output$table <- renderTable({ if(!is.null(input$checkbox)) mtcars %&g

假设我有以下UI:

ui <- fluidPage(
checkboxGroupInput("checkbox", "", choices = colnames(mtcars)),
tableOutput("table")
)
和这个不一样吗

server <- function(input, output) {

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

shinyApp(ui, server)

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

function (..., cancelOutput = FALSE) 
{
    dotloop(function(item) {
        if (!isTruthy(item)) {
            if (isTRUE(cancelOutput)) {
                cancelOutput()
            }
            else {
                reactiveStop(class = "validation")
            }
        }
    }, ...)
    if (!missing(..1)) 
        ..1
    else invisible()
}
基本上发生的事情是,它在您传入的所有值上循环,并检查它们是否看起来“真实”,而不仅仅是检查null。如果是这样,它将取消输出。而
如果
语句只会有条件地执行一个代码块,则不一定会取消输出。例如,当你有这个街区的时候

server <- function(input, output) {
    output$table <- renderTable({
      if(!is.null(input$checkbox)) 
         mtcars %>% select(input$checkbox)
      print("ran")
    })
}
req()
基本上中止块的其余部分,因此如果
req
不是“truthy”值,则
print()
不会运行。它只是使防止不必要的代码运行变得更容易

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