I'm writing a function that takes several parameters, strings or vectors of strings that correspond to attributes I'd like to filter on. I'd also like to write my function so that when a filter attribute isn't specified, it is simply ignored and the other filter attributes work.

Why does this shorthand using quo not work this way, and how can I change it so that it does?

library(dplyr); library(datasets)
filterhec <- function(hair = '', eyecolor = '', sex = '') {
  hec <- as.data.frame(datasets::HairEyeColor)

    # Filter condition variable, which changes depending on parameters
    fcond <- quo(
      (ifelse(hair == '', 1, Hair == hair)) & 
      (ifelse(all(eyecolor == ''), 1, Eye %in% eyecolor)) & 
      (ifelse(sex == '', 1, Sex == sex)))

  filter(hec, !!fcond)
}

filterhec(hair = 'Black', eye = c('Brown', 'Blue'))
#     Hair   Eye    Sex Freq
# 1  Black Brown   Male   32
# 2  Brown Brown   Male   53
# 3    Red Brown   Male   10
# 4  Blond Brown   Male    3
# 5  Black  Blue   Male   11
# 6  Brown  Blue   Male   50
# 7    Red  Blue   Male   10
# 8  Blond  Blue   Male   30
# 9  Black Hazel   Male   10
#
# ^Expected dataframe where Hair is always 'Black' and Eye is 'Brown' or 'Blue' 
1

There are 1 best solutions below

0
On

The arguments of your function are already quoted as character vectors and the variables on which you filter are also hard coded. Therefore, I don't think there is any need for quo. You can do it like this:

library(dplyr)
library(datasets)

filterhec <- function(hair = NULL, eyecolor = NULL, sex = NULL) {
  hec <- as.data.frame(datasets::HairEyeColor)

  filter(
    hec,
    if (is.null(hair)) 1 else Hair == hair,
    if (is.null(eyecolor)) 1 else Eye %in% eyecolor,
    if (is.null(sex)) 1 else Sex == sex
  )
}

filterhec(hair = 'Black', eye = c('Brown', 'Blue'))
#>    Hair   Eye    Sex Freq
#> 1 Black Brown   Male   32
#> 2 Black  Blue   Male   11
#> 3 Black Brown Female   36
#> 4 Black  Blue Female    9