Home > Net >  Use value as logical operator in R
Use value as logical operator in R

Time:03-12

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:

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!

CodePudding user response:

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