Search code examples
rfunctiondplyrfilter

How to include variables in custom filter function for dataframe?


I can't seem to get my R function to work which is designed to filter (dplyr) a data frame based on the filter value (character) and filter field input parameters. Here is my setup code:

df <- data.frame(a=c(1,2,3,4),temp=c("a","b","c","d"))
 
filt_func <- function(input_df,filter_value,filter_field){
  filt_df <- input_df %>% dplyr::filter(grepl(filter_value,filter_field))
}

Now, when I run this without using a function it works?! Working code:

> df %>% dplyr::filter(grepl("d", temp))
  a temp
1 4    d

However, my function does not!

> output <- filt_func(df,"d",temp)
Error in `dplyr::filter()`:
i In argument: `grepl(filter_value, filter_field)`.
Caused by error in `is.factor()`:
! object 'temp' not found
Run `rlang::last_trace()` to see where the error occurred.  

Putting quotes around "temp" enables the code to run but the output is empty.

output <- filt_func(df,"d","temp")

I'm sure this is something silly but I've been starting at this too long and it's been a while since I coded functions. I tried adding return(filt_df) to the function but that didn't help.


Solution

  • You have to either get the string variable:

    filt_func <- function(input_df,filter_value,filter_field){
      filt_df <- input_df %>% dplyr::filter(grepl(filter_value,get(filter_field)))
      filt_df
    }
    
    filt_func(df,"d","temp")
    

    Or enclose it with {{}}:

    filt_func <- function(input_df,filter_value,filter_field){
      filt_df <- input_df %>% dplyr::filter(grepl(filter_value,{{filter_field}}))
      filt_df
    }
    
    filt_func(df,"d",temp)
    

    Both give:

      a temp
    1 4    d