Skip to content

Instantly share code, notes, and snippets.

@gadenbuie
Last active August 17, 2021 05:13
Show Gist options
  • Save gadenbuie/3c3711003948c74b5f4ca8053186108c to your computer and use it in GitHub Desktop.
Save gadenbuie/3c3711003948c74b5f4ca8053186108c to your computer and use it in GitHub Desktop.
`?` <- function(condition, result) {
if (missing(result)) return(
utils::`?`(deparse(substitute(condition)))
)
result <- substitute(result)
if (!is.call(result) || !identical(result[[1]], as.symbol(':'))) {
stop("Invalid syntax. Expected <condition> ? <if_true> : <if_false>", call. = FALSE)
}
eval(call("if", condition, result[[2]], result[[3]]))
}
TRUE ? "yes" : "no"
#> [1] "yes"
FALSE ? "yes" : "no"
#> [1] "no"
TRUE ? (1:3) : (4:6)
#> [1] 1 2 3
FALSE ? (1:3) : (4:6)
#> [1] 4 5 6
TRUE ? "yes"
#> Error: Invalid syntax. Expected <condition> ? <if_true> : <if_false>
maybe <- function() as.logical(sample(0:1, 1))
message(
"The dog ", maybe() ? "did" : "didn't", " eat my homework."
)
#> The dog did eat my homework.
# And help still (mostly) works
?runif
# https://git.io/JIP0C
# thanks @jimhester
# https://gist.github.com/jimhester/3ef5b148e03999a7b5124f93b0c1f404
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment