Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using match.fun with multiple inputs and filter in R

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading