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 names not found in v

partial

whether partial matching is allowed

errname

optional, name to be reported in any error messages; defaults to deparse1(substitute(v))

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:

An informative error is raised under any of the following conditions:

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)
))


[Package statnet.common version 4.12.0 Index]