Skip to contents

Add labels for values that don't already have them in a labelled vector.

Usage

lbl_add(x, ...)

lbl_add_vals(x, labeller = as.character, vals = NULL)

Arguments

x

A labelled vector

...

Arbitrary number of label placeholders created with lbl() indicating the value/label pairs to add.

labeller

A function that takes values being added as an argument and returns the labels to associate with those values. By default, uses the values themselves after converting to character.

vals

Vector of values to be labelled. If NULL, labels all unlabelled values that exist in the data.

Value

A labelled vector

See also

Examples

x <- haven::labelled(
  c(100, 200, 105, 990, 999, 230),
  c(`Unknown` = 990, NIU = 999)
)

# Add new labels manually
lbl_add(
  x,
  lbl(100, "$100"),
  lbl(105, "$105"),
  lbl(200, "$200"),
  lbl(230, "$230")
)
#> <labelled<double>[6]>
#> [1] 100 200 105 990 999 230
#> 
#> Labels:
#>  value   label
#>    100    $100
#>    105    $105
#>    200    $200
#>    230    $230
#>    990 Unknown
#>    999     NIU

# Add labels for all unlabelled values
lbl_add_vals(x)
#> <labelled<double>[6]>
#> [1] 100 200 105 990 999 230
#> 
#> Labels:
#>  value   label
#>    100     100
#>    105     105
#>    200     200
#>    230     230
#>    990 Unknown
#>    999     NIU

# Update label names while adding
lbl_add_vals(x, labeller = ~ paste0("$", .))
#> <labelled<double>[6]>
#> [1] 100 200 105 990 999 230
#> 
#> Labels:
#>  value   label
#>    100    $100
#>    105    $105
#>    200    $200
#>    230    $230
#>    990 Unknown
#>    999     NIU

# Add labels for select values
lbl_add_vals(x, vals = c(100, 200))
#> <labelled<double>[6]>
#> [1] 100 200 105 990 999 230
#> 
#> Labels:
#>  value   label
#>    100     100
#>    200     200
#>    990 Unknown
#>    999     NIU