Search code examples
rfunctiondplyrtidyverserlang

Recognition of a function input by filter in R?


In my foo() call below, is there a way for the input of filter_var = (i.e., test) to be recognized inside the function?

Right now, the input is not recognized.

library(tidyverse)
library(rlang)

foo <- function(..., filter_var = NULL){

filter_var <- rlang::ensyms(filter_var)
  
dat <- expand_grid(...)  

dat %>%
filter(
  
    {{filter_var}} != "A"   ## HERE `filter_var` is not recognized. 
  )
}

foo(study = 1:2, test = LETTERS[1:2], filter_var = test)

#  study test 
#  <int> <chr>
#1     1 A    
#2     1 B    
#3     2 A    
#4     2 B 

Solution

  • You can't combine ensym and {{}}. Either use {{}} without the explict ensym

    foo <- function(..., filter_var = NULL){
      dat <- expand_grid(...)  
      dat %>%
        filter({{filter_var}} != "A")
    }
    
    foo(study = 1:2, test = LETTERS[1:2], filter_var = test)
    

    or use !! with the ensym (note that you're only decoding one symbol so use ensym rather than ensyms).

    foo <- function(..., filter_var = NULL){
      filter_var <- rlang::ensym(filter_var)
      dat <- expand_grid(...)  
      dat %>%
        filter(!!filter_var != "A")
    }