Learn R Programming

ipumsr (version 0.4.5)

lbl_collapse: Collapse labelled values to labels that already exist

Description

Converts values to a new value based on their label and value in a labelled vector. If the newly assigned value does not match an already existing labelled value, the smallest value's label is used. Ignores any value that does not have a label.

Usage

lbl_collapse(x, .fun)

Arguments

x

A labelled vector

.fun

A function that takes .val and .lbl (the values and labels) and returns the values of the label you want to change it to. It is passed to a function similar to as_function, so also accepts quosure-style lambda functions (that use values .val and .lbl). See examples for more information.

Value

A haven::labelled vector

See Also

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

Examples

Run this code
# NOT RUN {
x <- haven::labelled(
  c(10, 10, 11, 20, 30, 99, 30, 10),
  c(Yes = 10, `Yes - Logically Assigned` = 11, No = 20, Maybe = 30, NIU = 99)
)

lbl_collapse(x, ~(.val %/% 10) * 10)
# Notice that 90 get's NIU from 99 even though 90 didn't have a label in original

lbl_collapse(x, ~ifelse(.val == 10, 11, .val))
# But here 10 is assigned 11's label

# You can also use the more explicit function notation
lbl_collapse(x, function(.val, .lbl) (.val %/% 10) * 10)

# Or even the name of a function
collapse_function <- function(.val, .lbl) (.val %/% 10) * 10
lbl_collapse(x, "collapse_function")

# }

Run the code above in your browser using DataLab