Last active
June 19, 2021 02:40
-
-
Save robertzk/6c46305424e0439e967b to your computer and use it in GitHub Desktop.
ternary operator in R
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
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
Oh, even more awesome than I thought.