Building on the if else
foundation from the previous lesson,
we will explore two efficient alternatives: the ifelse
function and the case when
block.
ifelse
functionWhen we created an if else
block in the previous lesson,
it spanned several lines due to the requirement of incorporating curly
brackets after each conditional expression. However, if the actions
within these expressions are quite straightforward, we can opt for a
more condensed representation using the ifelse
function,
essentially boiling the block down to a single line.
Let's break down the structure of this function. The
ifelse(condition, a, b)
function encompasses three
components: the condition parameter, which is an expression
that will be evaluated and must result in a boolean value; the
a parameter, which contains the code to be executed if the
condition yields TRUE; and the b parameter, where the
code to run when the condition is FALSE resides. To illustrate
this concept further, we'll demonstrate how to condense the
if else
block from the 3rd code editor in the previous lesson
into a streamlined ifelse
statement.
One difference here is that the ifelse
function will
return the value of the expression that is executed, whereas the
if else
block will not return anything. This means that
we can assign the result of the ifelse
function to a
variable, as we did with y
in the example above, so
that we may print it out.
In the previous lesson, we explored the use of
if, else if, else
conditions to examine multiple scenarios.
While it is entirely possible to add more else if
statements
to encompass additional conditions, doing so can lead to extensive,
hard-to-maintain code. A more efficient and tidy approach is to utilize
the case_when
function, which enables us to inspect a
series of conditions and allot a value corresponding to the true
condition. Feel free to change the value of a to see the
different outputs.
Now let's see the same code but this time using
multiple if, else if, else
conditions.
This will have the same result, however as we can see
the code is much more verbose.