Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save moodymudskipper/3f3a1ab918a6a39b591642179475ae56 to your computer and use it in GitHub Desktop.
Save moodymudskipper/3f3a1ab918a6a39b591642179475ae56 to your computer and use it in GitHub Desktop.
infix operators on steroids
Not sure exactly how useful that would be but that'd be a fun small package.
The following `infix` function parses an expression containing
multiple infix operators so we can do things like `infix(x %is_between% y %and% z)`, i.e an "infix operation" with more than 2 parameters.
See example.
The name `infix` is not great.
```
infix <- function(x) {
x <- substitute(x)
args <- alist()
funs <- character(0)
while(length(x) > 1 && grepl("^\\%.*\\%$",deparse(x[[1]]))){
args <- c(x[[3]], args)
funs <- c(gsub("%","",deparse(x[[1]]),fixed=TRUE),funs)
x <- x[[2]]
}
fun <- paste(funs, collapse="/")
args <- c(x, args)
eval.parent(rlang::expr((!!as.name(fun))(!!!args)))
}
# define function using "/" separator
`is_between/and` <- function(x,y,z) {between(x,y,z)}
# infix will parse the expression and call the relevant function
x <- 5
y <- 1
z <- 10
infix(x %is_between% y %and% z)
# [1] TRUE
x <- 12
infix(x %is_between% y %and% z)
# [1] FALSE
```
@moodymudskipper
Copy link
Author

I think regular infix operators like %in% can still be used if the expression is wrapped inside force or identity, but it isn't tested.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment