% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/copy_labels.R
\name{copy_labels}
\alias{copy_labels}
\alias{copy_labels_from}
\title{Copy variable and value labels and SPSS-style missing value}
\usage{
copy_labels(from, to, .strict = TRUE)

copy_labels_from(to, from, .strict = TRUE)
}
\arguments{
\item{from}{A vector or a data.frame (or tibble) to copy labels from.}

\item{to}{A vector or data.frame (or tibble) to copy labels to.}

\item{.strict}{When \code{from} is a labelled vector, \code{to} have to be of the same
type (numeric or character) in order to copy value labels and SPSS-style
missing values. If this is not the case and \code{.strict = TRUE}, an error
will be produced. If \code{.strict = FALSE}, only variable label will be
copied.}
}
\description{
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.
}
\details{
Some base \R functions like \code{\link[base:subset]{base::subset()}} drop variable and
value labels attached to a variable. \code{copy_labels} could be used
to restore these attributes.

\code{copy_labels_from} is intended to be used with \pkg{dplyr} syntax,
see examples.
}
\examples{
library(dplyr)
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)
fdf <- df \%>\% filter(id < 3)
var_label(fdf) # some variable labels have been lost
fdf <- fdf \%>\% copy_labels_from(df)
var_label(fdf)

# Alternative syntax
fdf <- subset(df, id < 3)
fdf <- copy_labels(from = df, to = fdf)
}
