lbl_relabel: Modify value labels for a labelled vector

View source: R/lbl_helpers.R

lbl_relabelR Documentation

Modify value labels for a labelled vector

Description

Update the mapping between values and labels in a labelled vector. These functions allow you to simultaneously update data values and the existing value labels. Modifying data values directly does not result in updated value labels.

Use lbl_relabel() to manually specify new value/label mappings. This allows for the addition of new labels.

Use lbl_collapse() to collapse detailed labels into more general categories. Values can be grouped together and associated with individual labels that already exist in the labelled vector.

Unlabelled values will be converted to NA.

Usage

lbl_relabel(x, ...)

lbl_collapse(x, .fun)

Arguments

x

A labelled vector

...

Arbitrary number of two-sided formulas.

The left hand side should be a label placeholder created with lbl() or a value that already exists in the data.

The right hand side should be a function taking .val and .lbl arguments that evaluates to TRUE for all cases that should receive the label specified on the left hand side.

Can be provided as an anonymous function or formula. See Details section.

.fun

A function taking .val and .lbl arguments that returns the value associated with an existing label in the vector. Input values to this function will be relabeled with the label of the function's output value.

Can be provided as an anonymous function or formula. See Details section.

Details

Several ⁠lbl_*()⁠ functions include arguments that can be passed a function of .val and/or .lbl. These refer to the existing values and labels in the input vector, respectively.

Use .val to refer to the values in the vector's value labels. Use .lbl to refer to the label names in the vector's value labels.

Note that not all ⁠lbl_*()⁠ functions support both of these arguments.

Value

A labelled vector

See Also

Other lbl_helpers: lbl(), lbl_add(), lbl_clean(), lbl_define(), lbl_na_if(), zap_ipums_attributes()

Examples

x <- haven::labelled(
  c(10, 10, 11, 20, 21, 30, 99, 30, 10),
  c(
    Yes = 10, `Yes - Logically Assigned` = 11,
    No = 20, Unlikely = 21, Maybe = 30, NIU = 99
  )
)

# Convert cases with value 11 to value 10 and associate with 10's label
lbl_relabel(x, 10 ~ .val == 11)
lbl_relabel(x, lbl("Yes") ~ .val == 11)

# To relabel using new value/label pairs, use `lbl()` to define a new pair
lbl_relabel(
  x,
  lbl(10, "Yes/Yes-ish") ~ .val %in% c(10, 11),
  lbl(90, "???") ~ .val == 99 | .lbl == "Maybe"
)

# Collapse labels to create new label groups
lbl_collapse(x, ~ (.val %/% 10) * 10)

# These are equivalent
lbl_collapse(x, ~ ifelse(.val == 10, 11, .val))
lbl_relabel(x, 11 ~ .val == 10)

ipumsr documentation built on Sept. 12, 2024, 7:38 a.m.