standard evaluation version of dplyr filter appears to be ignored

171 Views Asked by At

I'm trying to write a function in which a user will specify a dataframe and a column name (string) and have the string be passed to the dplyr filter function.

I am confident that I am supposed to be using filter_, but I cannot seem to get it to behave as expected.

Consider the dataframe, data below. If I want to pipe it to the NSE version of filter this is accomplished as shown below

data <- data.frame(column1 = c(-1:10))

data %>% filter(column1 >= 0)

#    column1
# 1        0
# 2        1
# 3        2
# 4        3
# 5        4
# 6        5
# 7        6
# 8        7
# 9        8
# 10       9
# 11      10

However, when I attempt to implement this within a function, the filter appears to be ignored as shown below.

filter_fn <- function(d_in,column){
  criteria <- interp(~ as.name(column) >= 0)  
  d_out = d_in %>% filter_(criteria)
  return(d_out)
}

filter_fn(data, "column1")

#    column1
# 1       -1
# 2        0
# 3        1
# 4        2
# 5        3
# 6        4
# 7        5
# 8        6
# 9        7
# 10       8
# 11       9
# 12      10

This isn't a nuance of passing the params through a function either as the exact same result is returned from.

data %>% filter_(interp(~ as.name(column) >= 0))

QUESTION: How can I write a function with the desired parameters that will filter a dataframe using dplyr?

0

There are 0 best solutions below