Skip to content

Instantly share code, notes, and snippets.

@yjunechoe
Created March 26, 2024 14:30
Show Gist options
  • Save yjunechoe/07144b40e23e9ddc53605c03dd26dc56 to your computer and use it in GitHub Desktop.
Save yjunechoe/07144b40e23e9ddc53605c03dd26dc56 to your computer and use it in GitHub Desktop.
ternary op in R
lobstr::ast(T ? F : 1)
`%?%` <- function(e1, e2) {
e2_expr <- substitute(e2)
if (e1) {
return(eval.parent(e2_expr[[2]]))
} else {
return(eval.parent(e2_expr[[3]]))
}
}
`?` <- function(e1, e2) {
e1_expr <- substitute(e1)
if (missing(e2)) {
return(do.call(utils::`?`, list(e1_expr)))
}
e2_expr <- substitute(e2)
e1_is_sym <- is.symbol(e1_expr)
e2_is_colon_call <- is.call(e2_expr) && identical(e2_expr[[1]], quote(`:`))
if (!e1_is_sym) {
return(eval.parent(substitute(`%?%`(e1_expr, e2_expr))))
}
if (!e2_is_colon_call) {
return(do.call(utils::`?`, list(e1_expr, e2_expr)))
}
e1_is_help <- !exists(e1_expr, parent.frame())
if (e1_is_help) {
return(do.call(utils::`?`, list(e1_expr, e2_expr)))
}
e1_val <- eval.parent(e1_expr)
e1_is_cond <- isTRUE(e1_val) || isFALSE(e1_val)
if (e1_is_cond) {
warning("`", deparse(e1_expr), "` is ambiguous!", call. = FALSE)
return(eval.parent(substitute(`%?%`(e1_expr, e2_expr))))
} else {
return(do.call(utils::`?`, list(e1_expr, e2_expr)))
}
}
@yjunechoe
Copy link
Author

1 == 1 ? "y" : "n"
#> [1] "y"
1 == 2 ? "y" : "n"
#> [1] "n"

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