% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/as_factor.R
\name{as_factor}
\alias{as_factor}
\alias{as_factor.data.frame}
\alias{as_factor.haven_labelled}
\alias{as_factor.labelled}
\title{Convert labelled vectors to factors}
\usage{
\method{as_factor}{data.frame}(x, ..., only_labelled = TRUE)

\method{as_factor}{haven_labelled}(
  x,
  levels = c("default", "labels", "values", "both"),
  ordered = FALSE,
  ...
)

\method{as_factor}{labelled}(
  x,
  levels = c("default", "labels", "values", "both"),
  ordered = FALSE,
  ...
)
}
\arguments{
\item{x}{Object to coerce to a factor.}

\item{...}{Other arguments passed down to method.}

\item{only_labelled}{Only apply to labelled columns?}

\item{levels}{How to create the levels of the generated factor:
\itemize{
\item "default": uses labels where available, otherwise the values.
Labels are sorted by value.
\item "both": like "default", but pastes together the level and value
\item "label": use only the labels; unlabelled values become \code{NA}
\item "values": use only the values
}}

\item{ordered}{If \code{TRUE} create an ordered (ordinal) factor, if
\code{FALSE} (the default) create a regular (nominal) factor.}
}
\description{
The base function \code{as.factor()} is not a generic, but \code{\link[forcats:as_factor]{forcats::as_factor()}}
is. haven provides \code{as_factor()} methods for \code{\link[=labelled]{labelled()}} and
\code{\link[=labelled_spss]{labelled_spss()}} vectors, and data frames. By default, when applied to a
data frame, it only affects labelled columns.
}
\details{
Includes methods for both class \code{haven_labelled} and \code{labelled}
for backward compatibility.
}
\examples{
x <- labelled(sample(5, 10, replace = TRUE), c(Bad = 1, Good = 5))

# Default method uses values where available
as_factor(x)
# You can also extract just the labels
as_factor(x, levels = "labels")
# Or just the values
as_factor(x, levels = "values")
# Or combine value and label
as_factor(x, levels = "both")

# as_factor() will preserve SPSS missing values from values and ranges
y <- labelled_spss(1:10, na_values = c(2, 4), na_range = c(8, 10))
as_factor(y)
# use zap_missing() first to convert to NAs
zap_missing(y)
as_factor(zap_missing(y))
}
