Create a data frame when filter() returns no data

library(tidyverse)
# Toy data
df <- tibble(
  name = c("A", "B", "C"),
  id = c(123, 456, 789),
  age = c(20, 22, 30)
)

# Apply filtering
df %>% 
  filter(age > 35)
#> # A tibble: 0 x 3
#> # ... with 3 variables: name <chr>, id <dbl>, age <dbl>

When I apply the filtering filter(age > 35), there is no data for obvious reasons. In this situation, how can I create a data frame where name and id get "" and the age column gets "Nothing to check".

The data frame, say, df_wanted should look like this:

# A tibble: 1 x 3
  name  id    age             
  <chr> <chr> <chr>           
1 ""    ""    Nothing to check

You could wrap filter() in your own function, like this:

library(dplyr)
df <- tibble(
  name = c("A", "B", "C"),
  id = c(123, 456, 789),
  age = c(20, 22, 30)
)
FilterFunc <- function(DF, VAL) {
  tmp <- DF |> filter(age > VAL)
  if(nrow(tmp) == 0) {
    tmp <- tibble(name = "", id = "", age = "Nothing to check")
  }
 return(tmp)
  
}
FilterFunc(df, 35)       
#> # A tibble: 1 x 3
#>   name  id    age             
#>   <chr> <chr> <chr>           
#> 1 ""    ""    Nothing to check
FilterFunc(df, 21)
#> # A tibble: 2 x 3
#>   name     id   age
#>   <chr> <dbl> <dbl>
#> 1 B       456    22
#> 2 C       789    30

Created on 2022-08-26 by the reprex package (v2.0.1)

1 Like

@FJCC Many thanks for teaching the cool trick! This solution is just what I wanted :slight_smile:

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.