Become an expert in R — Interactive courses, Cheat Sheets, certificates and more!
Get Started for Free

when

Match/validate a set of conditions for an object and continue with the action associated with the first valid match.


Description

when is a 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.

Usage

when(., ...)

Arguments

.

the value to match against

...

formulas; each containing a condition as LHS and an action as RHS. named arguments will define additional values.

Value

The value resulting from the action of the first valid match/condition is returned. If no matches are found, and no default is given, NULL will be returned.

Validity of the conditions are tested with isTRUE, or equivalently with identical(condition, TRUE). 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 ifelse function.

Examples

1:10 %>%
  when(
    sum(.) <=  50 ~ sum(.),
    sum(.) <= 100 ~ sum(.)/2,
    ~ 0
  )

1:10 %>%
  when(
    sum(.) <=   x ~ sum(.),
    sum(.) <= 2*x ~ sum(.)/2,
    ~ 0,
    x = 60
  )

iris %>%
  subset(Sepal.Length > 10) %>%
  when(
    nrow(.) > 0 ~ .,
    ~ iris %>% head(10)
  )

iris %>%
  head %>%
  when(nrow(.) < 10 ~ .,
       ~ stop("Expected fewer than 10 rows."))

purrr

Functional Programming Tools

v0.3.4
GPL-3 | file LICENSE
Authors
Lionel Henry [aut, cre], Hadley Wickham [aut], RStudio [cph, fnd]
Initial release

We don't support your browser anymore

Please choose more modern alternatives, such as Google Chrome or Mozilla Firefox.