Converts values to a new value (that may or may not exist) based on their label and value in a labelled vector. Ignores any value that does not have a label.

lbl_relabel(x, ...)

Arguments

x

A labelled vector

...

Two-sided formulas where the left hand side is a label placeholder (created with the lbl function) or a value that already exists in the data and the right hand side is a function that returns a logical vector that indicates which labels should be relabeled. The right hand side 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

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_relabel(
  x,
  lbl(10, "Yes/Yes-ish") ~ .val %in% c(10, 11),
  lbl(90, "???") ~ .val == 99 | .lbl == "Maybe"
)
#> <labelled<double>[8]>
#> [1] 10 10 10 20 90 90 90 10
#> 
#> Labels:
#>  value       label
#>     10 Yes/Yes-ish
#>     20          No
#>     90         ???

# If relabelling to labels that already exist, don't need to specify both label
# and value:
# If just bare, assumes it is a value:
lbl_relabel(x, 10 ~ .val == 11)
#> <labelled<double>[8]>
#> [1] 10 10 10 20 30 99 30 10
#> 
#> Labels:
#>  value label
#>     10   Yes
#>     20    No
#>     30 Maybe
#>     99   NIU
# Use single argument to lbl for the label
lbl_relabel(x, lbl("Yes") ~ .val == 11)
#> <labelled<double>[8]>
#> [1] 10 10 10 20 30 99 30 10
#> 
#> Labels:
#>  value label
#>     10   Yes
#>     20    No
#>     30 Maybe
#>     99   NIU
# Or can used named arguments
lbl_relabel(x, lbl(.val = 10) ~ .val == 11)
#> <labelled<double>[8]>
#> [1] 10 10 10 20 30 99 30 10
#> 
#> Labels:
#>  value label
#>     10   Yes
#>     20    No
#>     30 Maybe
#>     99   NIU