as_factor: Coerce a defined vector to a factor

View source: R/as_factor.R

as_factorR Documentation

Coerce a defined vector to a factor

Description

as_factor() converts a defined() vector into a standard R factor. If value labels are present, they are turned into factor levels via haven::as_factor(). Otherwise, the underlying values are converted with base::factor().

Usage

as_factor(x, ...)

## S3 method for class 'haven_labelled_defined'
as_factor(x, strip_attributes = TRUE, ...)

Arguments

x

A vector created with defined().

...

Reserved for future extensions.

strip_attributes

Logical; should semantic metadata attributes (such as label, unit, definition, and namespace) be removed from the returned vector? Defaults to TRUE.

Details

Use strip_attributes = TRUE when flattening or preparing data for external pipelines, but keep the default when working with defined vectors directly.

Value

A factor vector.

Examples

sex <- defined(
  c(0, 1, 1, 0),
  label  = "Sex",
  labels = c("Female" = 0, "Male" = 1)
)

as_factor(sex)
as_factor(sex, strip_attributes = FALSE)


dataset documentation built on Nov. 16, 2025, 5:06 p.m.