Home > Net >  Using match.fun with multiple inputs and filter in R
Using match.fun with multiple inputs and filter in R

Time:03-12

I have the following database along with a couple of input values:

operator <- ">="
amt <- 600
col <- "salary"

data <- data.frame(
   emp_id = c (1:5), 
   emp_name = c("Rick","Dan","Michelle","Ryan","Gary"),
   salary = c(623.3,515.2,611.0,729.0,843.25)
)

I've used match.fun using the original column name, but want to use the "col" value to specify which column name to filter on, similar to what it'd be below:

data %>% 
   filter(match.fun(operator)(col, amt))

I've tried adding "!!" to the front of col when it's in there, but that doesn't work. If I replace "col" with "salary" in the above table, that does work, but I want to be able to dynamically change what "col" is and have the function react to that.

CodePudding user response:

We may use .data to select the column based on the input col

library(dplyr)
data %>% 
   filter(match.fun(operator)(.data[[col]], amt))

-output

   emp_id emp_name salary
1      1     Rick 623.30
2      3 Michelle 611.00
3      4     Ryan 729.00
4      5     Gary 843.25

Or convert to symbol and evaluate (!!)

data %>% 
 filter(match.fun(operator)(!! rlang::sym(col), amt))
  emp_id emp_name salary
1      1     Rick 623.30
2      3 Michelle 611.00
3      4     Ryan 729.00
4      5     Gary 843.25

Or another option is to pass it in across

data %>% 
   filter(across(all_of(col), ~ match.fun(operator)(.x, amt)))
  emp_id emp_name salary
1      1     Rick 623.30
2      3 Michelle 611.00
3      4     Ryan 729.00
4      5     Gary 843.25

Or another option is to create an expression with paste/str_c and then parse

library(stringr)
data %>% 
  filter(!!rlang::parse_expr(str_c(col, operator, amt)))
  emp_id emp_name salary
1      1     Rick 623.30
2      3 Michelle 611.00
3      4     Ryan 729.00
4      5     Gary 843.25
  • Related