R Shiny - if 语句对reactive({}) 值失败

问题描述 投票:0回答:1

我正在构建一个应用程序,它应该具有一些功能,如果给定的反应式 df 不为空,则执行某些操作。但是,如果反应式 df 为空,则使用返回的reactive_df() 的另一个函数中的代码似乎无法运行。我尝试使用exists(),但是

我在我的服务器功能中尝试了以下操作:

filtered_df <- reactive({
    req(df, park_names())
    filtered_df <- df %>% filter(ParkNameColumn %in% park_names())

    print(nrow(filtered_df)) ##### THIS PRINTS REGARDLESS OF WHETHER filtered_df IS EMPTY OR NOT
    print(class(filtered_df)) ##### THIS PRINTS REGARDLESS OF WHETHER filtered_df IS EMPTY OR NOT

    return(filtered_df) 
)}

output$park_stats <- renderTable({

    print(nrow(filtered_df())) ##### THIS ONLY PRINTS IF filtered_df HAS NROWS > 0
    print(class(filtered_df())) ##### THIS ONLY PRINTS IF filtered_df HAS NROWS > 0

    if (nrow(filtered_df() > 0){ ##### CAUSES ERROR
       <some_functionality_that_renders_table_with_if_statement>

    if (exists(filtered_df()){ ##### CAUSES ERROR
       <some_functionality_that_renders_table_with_if_statement>
}

如何根据 df (或任何变量)是否存在/不为空来运行一些代码?

r shiny shiny-server shinyapps shiny-reactivity
1个回答
0
投票

您可以在

req
中使用
renderTable
。这样,如果reactive df“不存在”,则
renderTable
不会被执行。

output$park_stats <- renderTable({
    req(filtered_df())

    print(nrow(filtered_df())) 
    print(class(filtered_df())) 

    if (nrow(filtered_df()) > 0){
       <some_functionality_that_renders_table_with_if_statement>
})
© www.soinside.com 2019 - 2024. All rights reserved.