Skip to contents

Useful for letting x {comparison} NULL mean "match all values" in calls to dplyr::filter() and similar functions.

Usage

nullable_comparison(a, comparison_operator, b)

Arguments

a

First set of values for the comparison

comparison_operator

Comparison operator for the comparison, as a string, e.g. "==", ">=" "%in%".

b

Second set of values for the comparison, or NULL.

Value

A logical vector. Equivalent to b {comparison_operator} a if b is not NULL and to TRUE if b is NULL.

Examples


x <- 6
nullable_comparison(5, ">", x)
#> [1] FALSE

x <- NULL
nullable_comparison(5, ">", x)
#> [1] TRUE

df <- tibble::tibble(y = 1:6)
x <- 3
df |> dplyr::filter(
  nullable_comparison(y, ">", !!x),
  y < 5
)
#> # A tibble: 1 × 1
#>       y
#>   <int>
#> 1     4
x <- NULL
df |> dplyr::filter(
  nullable_comparison(y, ">", !!x),
  y < 5
)
#> # A tibble: 4 × 1
#>       y
#>   <int>
#> 1     1
#> 2     2
#> 3     3
#> 4     4