as_character() is the recommended method to convert a
defined() vector to a character type. It is metadata-aware and
ensures that the underlying data is character before coercion.
Base R's as.character() method applied to defined vectors
simply strips the class and returns the values as a plain character vector.
This is equivalent to calling as_character() with preserve_attributes = FALSE.
Usage
as_character(x, ...)
# S3 method for class 'haven_labelled_defined'
as_character(x, preserve_attributes = FALSE, ...)
# S3 method for class 'haven_labelled_defined'
as.character(x, ...)Arguments
- x
A vector created with
defined().- ...
Reserved for future use.
- preserve_attributes
Logical. If
TRUE, retainsunit,concept, andnamespaceattributes. Defaults toFALSE.
Details
If preserve_attributes = TRUE, the returned character vector retains
semantic metadata such as unit, concept, and namespace, though the
"defined" class itself is removed. If preserve_attributes = FALSE
(default), a plain character vector is returned with all attributes stripped.
For numeric-based defined vectors, as_character() throws an informative
error to avoid accidental coercion of non-character data.
Note: as.character() (base R) is supported but simply returns the raw
values, and does not preserve or warn about metadata loss.
Examples
# Recommended use
fruits <- defined(c("apple", "avocado", "kiwi"), label = "Fruit", unit = "kg")
as_character(fruits, preserve_attributes = TRUE)
#> [1] "apple" "avocado" "kiwi"
#> attr(,"unit")
#> [1] "kg"
# Strip metadata
as_character(fruits, preserve_attributes = FALSE)
#> [1] "apple" "avocado" "kiwi"
# Equivalent base R fallback
as.character(fruits)
#> [1] "apple" "avocado" "kiwi"
