match_with | R Documentation |
Function to check a variable using pattern matching.
match_with(x, ...)
x |
The variable to pattern-match |
... |
Pairs of one pattern (value or list or magrittr sequence) and one result function |
match_with(variable,
pattern, result-function,
...
If variable
matches a pattern
, result-function
is called. For comparing optional types, it is a better habit to
use match_with
than a conditional statement.
Each pattern
can be either:
an object or a primitive type (direct comparison with variable
),
a list (match if variable
is in the list),
a magrittr
functional sequence that matches if it returns variable
. The dot .
denotes the variable to be matched.
If result-function
takes no arguments, it will be called as is. Else, the only argument that will be sent is variable
.
You can also use the fallthrough function fallthrough()
to permit the matching to continue even if the current pattern is matched.
option(), none
library(magrittr) a <- 5 match_with(a, . %>% option(.), paste, none, function() "Error!" ) ## [1] 5 match_with(a, 1, function() "Matched exact value", list(2, 3, 4), function(x) paste("Matched in list:", x), . %>% if (. > 4) ., function(x) paste("Matched in condition:", x) ) ## [1] "Matched in condition: 5"
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.