Created
March 26, 2024 14:30
-
-
Save yjunechoe/07144b40e23e9ddc53605c03dd26dc56 to your computer and use it in GitHub Desktop.
ternary op in R
This file contains hidden or 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
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))) | |
} | |
} |
Author
yjunechoe
commented
Mar 26, 2024
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment