modifyVector: Use new information to update a vector. Similar in concept to...

View source: R/utils.R

modifyVectorR Documentation

Use new information to update a vector. Similar in concept to R's modify list

Description

Original purpose was to receive 2 named vectors, x and y, and copy "updated" named values from y into x. If x or y are not named, however, this will do something useful.

  • Both vectors are named: values in x for which y names match will be updated with values from y. If augment is true, then named values in y that are not present in x will be added to x.

  • If neither vector is named: returns a new vector with x as the values and y as the names. Same as returning names(x) <- y.

  • If x is not named, y is named: replaces elements in x with values of y where suitable (x matches names(y)). For matches, returns x = y[x] if names(y) include x.

  • If x is named, y is not named: returns y, but with names from x. Lengths of x and y must be identical.

  • If y is NULL or not provided, x is returned unaltered.

Usage

modifyVector(x, y, augment = FALSE, warnings = FALSE)

Arguments

x

vector to be updated, may be named or not.

y

possibly a named vector. If unnamed, must match length of x. If named, and length is shorter than x, then name-value pairs in x will be replaced with name-value pairs with y. If names in y are not in x, the augment argument determines the result.

augment

If TRUE, add new items in x from y. Otherwise, ignore named items in y that are not in x.

warnings

Defaults as FALSE. Show warnings about augmentation of the target vector.

Value

an updated vector

Author(s)

Paul Johnson

Examples

x <- c(a = 1, b = 2, c = 3)
y <- c(b = 22)
modifyVector(x, y)
y <- c(c = 7, a = 13, e = 8)
## If augment = TRUE, will add more elements to x
modifyVector(x, y, augment = TRUE)
modifyVector(x, y)
x <- c("a", "b", "c")
y <- c("income", "education", "sei")
## Same as names(x) <- y
modifyVector(x, y)
x <- c("a", "b", "c")
y <- c(a = "happy")
modifyVector(x, y)
y <- c(a = "happy", g = "glum")
## Will give error unless augment = TRUE
modifyVector(x, y, augment = TRUE)

kutils documentation built on Sept. 17, 2023, 5:06 p.m.