R Shiny - if statement on reactive({}) value failing

23 Views Asked by At

I am building an app which should have some functionality, that if a given reactive df is not empty, then do something. However, code in another function using the returned reactive_df() seems to not run if the reactive df is empty. I tried using exists(), but

I have tried the following in my server function:

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>
}

How do I run some code, based on whether a df (or any variable) exists/is not empty?

1

There are 1 best solutions below

0
Stéphane Laurent On

You can use req in the renderTable. In this way, if the reactive df "does not exist", the renderTable will not be executed.

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>
})