This function is the same as pmatch
, but it can throw an error instead of NA
if not match is found, and can be forced to throw the error if more than the desired number of matches is found.
Usage
pmatchSafe(
x,
table,
useFirst = FALSE,
error = TRUE,
ignoreCase = TRUE,
nmax = length(x),
...
)
Arguments
- x
Character: String to match.
- table
Character vector: Values to which to match.
- useFirst
Logical: If
TRUE
, and there is more than one match for a givenx
, then the first value intable
that matchesx
will be returned (without an error or warning).- error
Logical: If no match is found, return an error?
- ignoreCase
Logical: If
TRUE
(default), ignore the case of values inx
andtable
when checking for matches.- nmax
Positive numeric integer: Maximum allowable number of matches. If more than this number of matches is found, an error will be thrown (regardless of the value of
error
).- ...
Arguments to pass to
pmatch
.
Examples
pmatchSafe('ap', c('apples', 'oranges', 'bananas'))
#> [1] "apples"
pmatchSafe('AP', c('apples', 'oranges', 'bananas'))
#> [1] "apples"
pmatchSafe('AP', c('apples', 'oranges', 'bananas'),
ignoreCase = FALSE, error = FALSE)
#> [1] NA
pmatchSafe(c('ba', 'ap'), c('apples', 'oranges', 'bananas'))
#> [1] "bananas" "apples"
# No match:
tryCatch(
pmatchSafe('kumquats', c('apples', 'oranges', 'bananas')),
error = function(cond) FALSE
)
#> [1] FALSE
pmatchSafe('kumquats', c('apples', 'oranges', 'bananas'), error = FALSE)
#> [1] NA
pmatchSafe(c('ap', 'corn'), c('apples', 'oranges', 'bananas'), error = FALSE)
#> [1] "apples" NA
# Too many matches:
tryCatch(
pmatchSafe(c('ap', 'ba'), c('apples', 'oranges', 'bananas'), nmax = 1),
error=function(cond) FALSE
)
#> [1] FALSE