Skip to content

Instantly share code, notes, and snippets.

@jimhester
Last active November 9, 2021 19:17
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jimhester/3ef5b148e03999a7b5124f93b0c1f404 to your computer and use it in GitHub Desktop.
Save jimhester/3ef5b148e03999a7b5124f93b0c1f404 to your computer and use it in GitHub Desktop.
Ternary operator in R
``` r
`?` <- function(x, y) {
y <- substitute(y)
if (!is.call(y) || !identical(as.symbol(":"), y[[1]])) stop("Invalid", call. = FALSE)
eval(call("if", x, y[[2]], y[[3]]))
}
T ? 1
#> Error: Invalid
T ? 1 : 2
#> [1] 1
F ? 1 : 2
#> [1] 2
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment