Description Usage Arguments Details Value Examples
?
is an in-line if/else operator
1 | 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
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | # 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"
|
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.