Copies variable labels, value labels, and tagged NA metadata from a source
data frame to a target data frame. dplyr verbs such as dplyr::filter(),
dplyr::select() or dplyr::arrange() keep labels; they are lost by
base-R conversions and computations (e.g. as.numeric(), ifelse(),
arithmetic on labelled vectors), by merge() / rbind() of plain data
frames, or by a detour through CSV. copy_labels() restores them from
the original data.
Value
The target data frame with labels copied from the source. Only columns present in both data frames are affected. Columns only in the target are left unchanged.
Details
The variable label ("label") is always copied. The following are
copied only when the target column still holds the source's codes (a
numeric column whose values are observed values or labelled codes of the
source column):
"labels"— value labels"na_tag_map"— tagged NA mapping"na_tag_format"— tagged NA format (spss/stata/sas)"na_values","na_range"— SPSS missing-value definitions"class"— vector class (e.g.,haven_labelled)
A converted column (e.g. a factor from to_label()) or a summarised one
(e.g. group means) keeps its own type and gets the variable label only.
See also
Other labels:
drop_labels(),
find_var(),
set_na(),
to_character(),
to_label(),
to_labelled(),
to_numeric(),
unlabel(),
val_labels(),
var_label()
Examples
# as.numeric() drops the variable label
data_plain <- dplyr::mutate(survey_data, age = as.numeric(age))
attr(data_plain$age, "label")
#> NULL
# Restore it
data_plain <- copy_labels(data_plain, survey_data)
attr(data_plain$age, "label")
#> [1] "Age in years"
