map_values: Map Values

Description Usage Arguments Details Value Examples

View source: R/map_values.R

Description

Given a vector of values this returns the matched counterpart efficiently. Instead of applying a function to a vector that may have duplicates, you can apply the function to the unique values only and then pair them accordingly. A function is not needed or required and instead you could create a map manually.

Usage

1
map_values(values, map, replacement = NULL)

Arguments

values

character vector

map

named character vector - with restrictions

replacement

replacement value. If NULL (default) the original value is returned.

Details

This function only works when there is a unique pairing between old and new vectors. Therefore the 'map' must be a named vector of values where no value occurs more than once. Otherwise, the pairing will be ambiguous. That said, there can be more than one value that has the same mapped counterpart (e.g. name).

Values that do not appear in the map are return as-is and in the same position as the original vector

Value

vector of equal length

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
## Not run: 
# Duplicates cause failure
values <- 1:4
map    <- stats::setNames(c(1, 1:3), paste0("test", 1:4))
map_values(values, map)

# Works
values <- 1:4
map    <- stats::setNames(1:4, letters[1:4])
map_values(values, map)

# Works when length(map) > length(values)
values <- 1:3
map    <- stats::setNames(1:4, letters[1:4])
map_values(values, map)

# Works when values are out of order
values <- c(1, 3, 4)
map    <- stats::setNames(1:4, letters[1:4])
map_values(values, map)

## End(Not run)

cadenceinc/yolanda documentation built on Sept. 15, 2020, 5:20 a.m.