I want to filter some data. But I need the logical operator that links two conditions to be variable.
For example:
mtcars %>% filter(mpg>3 & cyl==6 MYCHOICE gear==4 MYCHOICE2 hp >110)
where MYCHOICE and MYCHOICE2 can be set as the string of MYCHOICE<-'And' ('&') or MYCHOICE<-'Or' ("|"):
I also need it in the format such that this will work.
mtcars %>% conditionally(filter)(mpg>3 & cyl==6 MYCHOICE gear==4 MYCHOICE2 hp >110,execute=TRUE)
conditionally <- function(fun){
function(..., execute) {
if (execute) fun(...) else ..1
}
}
CodePudding user response:
You can define a new operator to use instead of & and |. But it can’t be MYCHOICE — custom operators in R need to surrounded by %…%. You could go for %MYCHOICE% but I suggest something a little less verbose, e.g.:
`%.%` <- `&`
mtcars %>% filter(mpg > 3 & (cyl == 6) %.% (gear == 4) %.% (hp > 110))
(Note the parentheses around individual terms to ensure correct operator precedence.)
You can set %.% to whatever operator you want. If you want to set it based on a string, you could use e.g. switch:
choice <- 'And'
`%.%` <- switch(choice, And = `&`, Or = `|`)
