match_names {statnet.common} | R Documentation |
Construct a named vector with semantics useful for parameter vectors
Description
This is a helper function that constructs a named vector with names
in names
with values taken from v
and optionally default
,
performing various checks. It supersedes vector.namesmatch()
.
Usage
match_names(v, names, default = NULL, partial = TRUE, errname = NULL)
Arguments
v |
a vector |
names |
a character vector of element names |
default |
value to be used for elements of |
partial |
whether partial matching is allowed |
errname |
optional, name to be reported in any error messages;
defaults to |
Details
If v
is not named, it is required to be the same length as
names
and is simply given the corresponding names. If it is
named, nonempty names are matched to the corresponding elements of
names
, with partial matching supported.
Default values can be specified by the caller in default
or by
the end-user by adding an element with an empty (""
) name in
addition to the others. If given, the latter overrides the former.
Duplicated names in v
or names
are resolved sequentially,
though note the example below for caveat about partial matching.
Zero-length v
is handled as follows:
If length of
names
is empty, returnv
unchanged.If it is not and
default
is notNULL
, return thedefault
vector.Otherwise, raise an error.
An informative error is raised under any of the following conditions:
-
v
is not named but has length that differs from that ofnames
. More than one element of
v
has an empty name.Not all elements of
names
are matched by an element ofv
, and no default is specified.Not all elements of
v
are used up for elements ofnames
.There is ambiguity that
pmatch()
cannot resolve.
Value
A named vector with names names
(in that order). See
Details.
Note
At this time, passing partial=FALSE
will use a crude
sentinel to prevent partial matching, which in some, extremely
improbable, circumstances might not work.
Examples
# Unnamed:
test <- as.numeric(1:3)
stopifnot(identical(
match_names(test, c('a', 'c', 'b')),
c(a = 1, c = 2, b = 3)
))
# Named, reordered:
test <- c(c = 1, b = 2, a = 3)
stopifnot(identical(
match_names(test, c('a', 'c', 'b')),
c(a = 3, c = 1, b = 2)
))
# Default value specified by default= assigned to a
test <- c(c = 1, b = 2)
stopifnot(identical(
match_names(test, c('a', 'c', 'b'), NA),
c(a = NA, c = 1, b = 2)
))
# Default value specified in v assigned to a and b:
test <- c(c = 1, 2)
stopifnot(identical(
match_names(test, c('a', 'c', 'b')),
c(a = 2, c = 1, b = 2)
))
# Partial matching
test <- c(c = 1, 2)
stopifnot(identical(
match_names(test, c('a', 'cab', 'b')),
c(a = 2, cab = 1, b = 2)
))
# Multiple matching
test <- c(c = 1, 2, c = 3)
stopifnot(identical(
match_names(test, c('a', 'c', 'c')),
c(a = 2, c = 1, c = 3)
))
# Partial + multiple matching caveat: exact match will match first.
test <- c(c = 1, a = 2, ca = 3)
stopifnot(identical(
match_names(test, c('a', 'ca', 'ca')),
c(a = 2, ca = 3, ca = 1)
))