Skip to content

Instantly share code, notes, and snippets.

@robertzk
Last active June 19, 2021 02:40
Show Gist options
  • Save robertzk/6c46305424e0439e967b to your computer and use it in GitHub Desktop.
Save robertzk/6c46305424e0439e967b to your computer and use it in GitHub Desktop.
ternary operator in R
# A ternary operator in R.
if (!is.element("super", installed.packages()[,1])) { devtools::install_github("robertzk/super") }
`?` <- function(expr1, expr2) {
if (missing(expr2)) {
super::super(expr1)
} else {
expr2 <- substitute(expr2)
if (!(is.call(expr2) && identical(expr2[[1]], as.name(":")))) {
super::super(expr1, expr2)
} else {
condition <- eval.parent(expr1)
stopifnot(is.logical(condition) && length(condition) == 1)
if (condition) {
eval.parent(expr2[[2]])
} else {
eval.parent(expr2[[3]])
}
}
}
}
# > TRUE ? 1 : 2
# [1] 1
# > TRUE ? 2 : 1
# [1] 2
# > 1 == 2 ? 3 : 4
# [1] 4
@peterhurford
Copy link

This is cool! 👍

Rather than overloading ?, you could use %?% and then it could actually be used in codebases.

@robertzk
Copy link
Author

What do you mean? Putting it in your Imports doesn't overload other people's work.

@robertzk
Copy link
Author

And super::super takes care of ensuring correct behavior on base::"?"

@peterhurford
Copy link

Oh, even more awesome than I thought.

@peterhurford
Copy link

Make a package out of it? Put it in a package?

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