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.

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

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

## Examples

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)
#> <labelled<double>[8]>
#> [1] 10 10 10 20 30 90 30 10
#>
#> Labels:
#>  value label
#>     10   Yes
#>     20    No
#>     30 Maybe
#>     90   NIU
# 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))
#> <labelled<double>[8]>
#> [1] 11 11 11 20 30 99 30 11
#>
#> Labels:
#>  value                    label
#>     11 Yes - Logically Assigned
#>     20                       No
#>     30                    Maybe
#>     99                      NIU
# 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)
#> <labelled<double>[8]>
#> [1] 10 10 10 20 30 90 30 10
#>
#> Labels:
#>  value label
#>     10   Yes
#>     20    No
#>     30 Maybe
#>     90   NIU

# Or even the name of a function
collapse_function <- function(.val, .lbl) (.val %/% 10) * 10
lbl_collapse(x, "collapse_function")
#> <labelled<double>[8]>
#> [1] 10 10 10 20 30 90 30 10
#>
#> Labels:
#>  value label
#>     10   Yes
#>     20    No
#>     30 Maybe
#>     90   NIU