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

Use value as logical operator in R

I have a sample dataframe below along with a logical operator value:

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)
)

operator <- ">="

With this, I want to use a value to filter this dataframe based on the "operator" value. So right now it’s set to ">=" making the code look like this:

new_data <- data %>% 
  filter(salary >= 600)

Then, if I change the value of the operator to "<=", the function would change to this:

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

new_data <- data %>% 
  filter(salary <= 600)

This is part of a Shiny app, so I will have several of the operators as inputs, so ideally I don’t have to use if/else statements. It would be great if I could do something like this:

new_data <- data %>% 
  filter(salary operator 600)

However, I have no idea how to do this or if it’s possible. Appreciate the help!

>Solution :

We may use match.fun

library(dplyr)
data %>% 
   filter(match.fun(operator)(salary, 600))

-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
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