I want to filter my data frame based on a variable that may or may not exist. As an expected result, I want df to be filtered (if it has a filter variable) or the original, unfiltered df (if this variable is missing).
Here is a minimal example:
library(tidyverse) df1 <- tribble(~a,~b, 1L,"a", 0L, "a", 0L,"b", 1L, "b") df2 <- select(df1, b)
Filtering on df1 returns the desired result, filtered tibet.
filter(df1, a == 1)
But the second causes an error (presumably), since the variable is not in df.
filter(df2, a == 1) Error in filter_impl(.data, quo) : Evaluation error: object 'a' not found.
I tried filter_at , which would be an obvious choice, but it throws an error if there is no variable that matches the task.
filter_at(df2, vars(matches("a")), any_vars(. == 1L)) Error: `.predicate` has no matching columns
So my question is: is there a way to create conditional filtering that gives the expected result, preferably within tidyverse?