mapping {mappings}R Documentation

Generate a Mapping Function

Description

This function returns a function that does a simple mapping from one set of value to another. It is a function-generating function.

Usage

mapping(from, to, na = NA, ch.as.fact = TRUE)

Arguments

from

A vector. This is the domain of the function.

to

A vector of the same length as from. If omitted, then the names of from are taken as the domain, and the values as the values to map to. If from has no names, then to is equal to from (useful for re-ordering factor levels).

na

An alternative way to specify the value that NA maps to. Ignored if from contains NA.

ch.as.fact

A logical. Should the mapping return a factor instead of character?

Details

This function returns a function. When called with a vector argument x, this function will return a vector y of the same length as x and such that each element y[i] is equal to to[j] where j is the smallest integer such that from[j] == x[i], and NA if no such j exists.

Note: from will always be matched as a string, even if it is numeric. So, mapping(1, "A") and mapping("1", "A") are the same, and both functions will return "A" when called with either 1 or "1".

Value

A function that translates from from to to. The function also has an inverse which is a function that performs the inverse mapping.

See Also

inverse(), codomain(), domain(), remap(), text2mapping(), cut_mapping()

Examples


sex.mapping <- mapping(c("Female", "F", "Male", "M"), c(0, 0, 1, 1))
sex.mapping(c("Female", "Female", "Male", "F"))

sex.mapping <- mapping(0:1, c("Female", "Male"), na="Unknown")
sex.mapping(c(0, 1, NA, 0, 1, 1, 0))
inverse(sex.mapping)(c("Female", "Male", "Unknown"))

from <- c(0, 1, NA)
to <- c(NA, "Male", "Female")
x <- c(0, 1, NA, 0, 1, 1, 0)
sex.mapping <- mapping(c(0, 1, NA), c(NA, "Male", "Female"))
sex.mapping
sex.mapping(c(0, 1, NA, 0, 1, 1, 0))
inverse(sex.mapping)
inverse(sex.mapping)(c("Female", "Male", NA))

race.mapping <- mapping(c(
      "1"="WHITE",
      "2"="BLACK OR AFRICAN AMERICAN",
      "5"="AMERICAN INDIAN OR ALASKA NATIVE"))
race.mapping(1:5)


[Package mappings version 0.1 Index]