match_with {optional} | R Documentation |
Match With
Description
Function to check a variable using pattern matching.
Usage
match_with(x, ...)
Arguments
x |
The variable to pattern-match |
... |
Pairs of one pattern (value or list or magrittr sequence) and one result function |
Details
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 returnsvariable
. 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 isvariable
. You can also use the fallthrough functionfallthrough()
to permit the matching to continue even if the current pattern is matched.
See Also
option(), none
Examples
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"