Removes value labels for values that are not present in the data, and unused levels of factors. This is useful after filtering or subsetting, when some categories may no longer exist but their labels remain attached.
Details
This is useful after subsetting data (e.g., filtering out a category).
The removed category's label still exists on the variable, which can
cause confusing output in frequency() or codebook().
drop_labels() cleans this up by keeping only labels for values
actually present in the data. For factors, unused levels are dropped;
the variable label and the original codes of a to_label() factor are
kept.
By default, tagged NA labels are preserved (drop_na = FALSE) because
they represent missing value types, not substantive categories.
See also
Other labels:
copy_labels(),
find_var(),
set_na(),
to_character(),
to_label(),
to_labelled(),
to_numeric(),
unlabel(),
val_labels(),
var_label()
Examples
# After filtering, "Basic Secondary" no longer occurs but remains a level
data_subset <- dplyr::filter(survey_data, education != "Basic Secondary")
levels(data_subset$education)
#> [1] "Basic Secondary" "Intermediate Secondary" "Academic Secondary"
#> [4] "University"
data_clean <- drop_labels(data_subset)
levels(data_clean$education)
#> [1] "Intermediate Secondary" "Academic Secondary" "University"
# Value labels of labelled vectors
if (requireNamespace("haven", quietly = TRUE)) {
x <- haven::labelled(c(1, 2, 2), labels = c(low = 1, mid = 2, high = 3))
drop_labels(x) # the unused label "high" is removed
}
#> <labelled<double>[3]>
#> [1] 1 2 2
#>
#> Labels:
#> value label
#> 1 low
#> 2 mid
