lookup {zmisc}R Documentation

Lookup values from a lookup table

Description

The lookup() function implements lookup of certain strings (such as variable names) from a lookup table which maps keys onto values (such as variable labels or descriptions).

The lookup table can be in the form of a two-column data.frame, in the form of a named vector, or in the form of a list. If the table is in the form of a data.frame, the lookup columns should be named name (for the key) and value (for the value). If the lookup table is in the form of a named vector or list, the name is used for the key, and the returned value is taken from the values in the vector or list.

Original values are returned if they are not found in the lookup table. Alternatively, a default can be specified for values that are not found. Note that an NA in x will never be found and will be replaced with the default value. To specify different defaults for values that are not found and for NA values in x, the default must be crafted manually to achieve this.

Any names in x are not included in the result.

The lookuper() function returns a function equivalent to the lookup() function, except that instead of taking a lookup table as an argument, the lookup table is embedded in the function itself.

This can be very useful, in particular when using the lookup function as an argument to other functions that expect a function which maps character->character but do not offer a good way to pass additional arguments to that function.

Usage

lookup(x, lookup_table, default = x)

lookuper(lookup_table, default = NULL)

Arguments

x

A string vector whose elements are to be looked up.

lookup_table

The lookup table to use.

default

If a value is not found in the lookup table, the value will be taken from default. This must be a character vector of length 1 or the same length as x. Useful values include x (the default setting), NA, or "" (an empty string).

Value

The lookup() function returns string vector based on x, with values replaced with the lookup values from lookup_table. Any values not found in the lookup table are taken from default.

The lookuper() function returns a function that takes character vectors as its argument x, and returns either the corresponding values from the underlying lookup table, or the original values from x for those elements that are not found in the lookup table (or looks them up from the default).

Examples

fruit_lookup_vector <- c(a="Apple", b="Banana", c="Cherry")
lookup(letters[1:5], fruit_lookup_vector)
lookup(letters[1:5], fruit_lookup_vector, default = NA)

mtcars_lookup_data_frame <- data.frame(
  name = c("mpg", "hp", "wt"),
  value = c("Miles/(US) gallon", "Gross horsepower", "Weight (1000 lbs)"))
lookup(names(mtcars), mtcars_lookup_data_frame)

lookup_fruits <- lookuper(list(a="Apple", b="Banana", c="Cherry"))
lookup_fruits(letters[1:5])


[Package zmisc version 0.2.3 Index]