Title: | A Ternary Conditional Operator for R |
---|---|
Description: | A small language extension for succinct conditional assignment using `?` and `:`, emulating the conditional ternary operator syntax using in C, Java, JavaScript and other languages. |
Authors: | Gethin Davies [aut, cre] |
Maintainer: | Gethin Davies <[email protected]> |
License: | MIT + file LICENSE |
Version: | 0.1.2 |
Built: | 2025-02-16 03:30:12 UTC |
Source: | https://github.com/grddavies/rtern |
?
is an in-line if/else operator
lhs ? rhs
lhs ? rhs
lhs |
A logical expression, vector or matrix. |
rhs |
A pair of values separated by a colon i.e. |
The syntax for ? is as follows:
condition ? value_if_true : value_if_false
The condition is evaluated TRUE or FALSE as a Boolean expression.
On the basis of the evaluation of the Boolean condition, the entire expression
returns value_if_true
if condition
is true, but value_if_false
otherwise.
In the case where the condition is a vector/matrix of Boolean values, the
function returns a vector/matrix where each element is either value_if_true
or value_if_false
based on the truthiness of the elements of the object on
the left-hand side. In these cases the behaviour of ?
mimics ifelse.
Who has time for if/else?
One of the values in rhs
, depending on the truthiness of lhs
.
# Conditional evaluation 4 > 3 ? "it_was_true":"it_was_false" # > "it_was_true" FALSE ? "it_was_true":"it_was_false" # > "it_was_false" # Vectorised evaluation c(4, 2) < 3 ? "it_was_true":"it_was_false" # > "it_was_false" "it_was_true" # Conditional assignment with `<-` x <- 4 > 3 ? "it_was_true":"it_was_false" x # > "it_was_true" # Conditional assignment with `=` y <- 3 > 4 ? "it_was_true":"it_was_false" y # > "it_was_false" # Chaining `?` statements z <- FALSE ? "true":(FALSE ? "false,true":(TRUE ? "false,false,true":"all false")) z # > "false,false,true"
# Conditional evaluation 4 > 3 ? "it_was_true":"it_was_false" # > "it_was_true" FALSE ? "it_was_true":"it_was_false" # > "it_was_false" # Vectorised evaluation c(4, 2) < 3 ? "it_was_true":"it_was_false" # > "it_was_false" "it_was_true" # Conditional assignment with `<-` x <- 4 > 3 ? "it_was_true":"it_was_false" x # > "it_was_true" # Conditional assignment with `=` y <- 3 > 4 ? "it_was_true":"it_was_false" y # > "it_was_false" # Chaining `?` statements z <- FALSE ? "true":(FALSE ? "false,true":(TRUE ? "false,false,true":"all false")) z # > "false,false,true"