Applying a filter using only the non-missing arguments of a function

Viewed 68

How can I apply a filter in R using only the non-missing arguments of a function?

Let’s say I have this function:

extract_data <- function(.a = NA, .b = NA, .c = NA) {
  df %>% 
    filter(a == .a,
           b == .b,
           c == .c)
}

If I run extract_data(.a = 1, .c == 1), I’d like the function to return all rows of df where a = 1 and c = 1, regardless of the value of b.

Clearly, the function above takes into account the value of b and will only return rows where a = 1, c = 1, and b = NA. How can I modify the function to ignore b when its value is NA?

I am looking for a dynamic solution since my actual function has more arguments than used in the example above.

1 Answers

Here's an example that might help you:

library(tidyverse)
extract_data <- function(df, ...) {
  condition = enquos(...)
  df %>% 
    filter(!!!condition)
}

extract_data(mtcars, mpg > 25, gear > 4)
#   mpg cyl  disp  hp drat    wt qsec vs am gear carb
#1 26.0   4 120.3  91 4.43 2.140 16.7  0  1    5    2
#2 30.4   4  95.1 113 3.77 1.513 16.9  1  1    5    2

extract_data(mtcars, mpg > 25)
#    mpg cyl  disp  hp drat    wt  qsec vs am gear carb
# 1 32.4   4  78.7  66 4.08 2.200 19.47  1  1    4    1
# 2 30.4   4  75.7  52 4.93 1.615 18.52  1  1    4    2
# 3 33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1
# 4 27.3   4  79.0  66 4.08 1.935 18.90  1  1    4    1
# 5 26.0   4 120.3  91 4.43 2.140 16.70  0  1    5    2
# 6 30.4   4  95.1 113 3.77 1.513 16.90  1  1    5    2

extract_data(mtcars, gear == 4, carb == 1)
#    mpg cyl  disp hp drat    wt  qsec vs am gear carb
# 1 22.8   4 108.0 93 3.85 2.320 18.61  1  1    4    1
# 2 32.4   4  78.7 66 4.08 2.200 19.47  1  1    4    1
# 3 33.9   4  71.1 65 4.22 1.835 19.90  1  1    4    1
# 4 27.3   4  79.0 66 4.08 1.935 18.90  1  1    4    1

In this case you don't need to hard code any variables to be checked in the filter. You can just define them in the function call.

Note: this approach gives you full flexibility in defining the filter conditions in the function call. For example:

extract_data(mtcars, gear == 4 & (carb == 1 | hp > 100))

When using ... in the function definition, make sure to name the other function arguments to avoid confusion.

Related