when | R Documentation |
if
-else
for pipesA flavour of pattern matching (or an if-else abstraction) in which a value .
is matched against a sequence ...
of condition-action sets. When a valid
match/condition is found, the action is executed and the result of the action is returned.
when(., ...)
. |
Value to match against. |
... |
Formulas, each containing a condition as LHS and an action as RHS. Named arguments will define additional values. Dynamic dots are supported. |
Condition-action sets are written as formulas with conditions as left-hand sides (LHS) and actions as right-hand sides (RHS). A formula with only a
right-hand side will be treated as a condition which is always satisfied. For such a default case one can also omit the ~
symbol, but note that its value
will then be evaluated early. Any named argument will be made available in all conditions and actions, which is useful in avoiding repeated temporary
computations or temporary assignments.
Validity of the conditions are tested with base::isTRUE()
. In other words conditions resulting in more than one logical will never be valid. Note that the
input value is always treated as a single object, as opposed to the base::ifelse()
function.
This function is copied over from package purrr since it has been deprecated with the release of purrr 1.0. pal::when()
can be used as a drop-in replacement for purrr::when()
.
All credits go to the original authors of purrr::when()
as of 2022-12-21.
The value resulting from the action of the first matched condition, or NULL
if no matches are found and no default is given.
1:10 |> pal::when(sum(.) <= 50 ~ sum(.),
sum(.) <= 100 ~ sum(.)/2L,
~ 0L)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.