This function copies variable and value labels (including missing values) from one vector to another or from one data frame to another data frame. For data frame, labels are copied according to variable names, and only if variables are the same type in both data frames.

copy_labels(from, to)

copy_labels_from(to, from)

Arguments

from

A vector or a data.frame (or tibble) to copy labels from.

to

A vector or data.frame (or tibble) to copy labels to.

Details

Some base R functions like subset drop variable and value labels attached to a variable. copy_labels coud be used to restore these attributes.

copy_labels_from is intended to be used with dplyr syntax, see examples.

Examples

library(dplyr)
#> #> Attachement du package : ‘dplyr’
#> The following object is masked from ‘package:testthat’: #> #> matches
#> The following objects are masked from ‘package:stats’: #> #> filter, lag
#> The following objects are masked from ‘package:base’: #> #> intersect, setdiff, setequal, union
df <- tibble( id = 1:3, happy = factor(c('yes', 'no', 'yes')), gender = labelled(c(1, 1, 2), c(female = 1, male = 2)) ) %>% set_variable_labels( id = "Individual ID", happy = "Are you happy?", gender = "Gender of respondent" ) var_label(df)
#> $id #> [1] "Individual ID" #> #> $happy #> [1] "Are you happy?" #> #> $gender #> [1] "Gender of respondent" #>
fdf <- df %>% filter(id < 3) var_label(fdf) # some variable labels have been lost
#> $id #> [1] "Individual ID" #> #> $happy #> NULL #> #> $gender #> [1] "Gender of respondent" #>
fdf <- fdf %>% copy_labels_from(df) var_label(fdf)
#> $id #> [1] "Individual ID" #> #> $happy #> [1] "Are you happy?" #> #> $gender #> [1] "Gender of respondent" #>
# Alternative syntax fdf <- subset(df, id < 3) fdf <- copy_labels(from = df, to = fdf)