as_character: Coerce to character vector

View source: R/defined.R

as.characterR Documentation

Coerce to character vector

Description

Base R's as.character() does not support custom classes like defined. Calling as.character() on a defined vector will drop all metadata and class information, which equals to as_character(x, preserve_attributes = FALSE).

as_character() is the recommended method to convert a defined vector to character. It is metadata-aware and ensures that the underlying data is character before coercion.

Usage

as.character(x, ...)

## S3 method for class 'haven_labelled_defined'
as.character(x, ...)

as_character(x, ...)

## S3 method for class 'haven_labelled_defined'
as_character(x, preserve_attributes = FALSE, ...)

Arguments

x

A vector created with defined.

...

Further arguments passed to internal methods (not used).

preserve_attributes

Defaults to FALSE. If set to TRUE, in which case the unit, concept and namespace attributes will be preserved, but the returned value will otherwise become a base R character vector. If false, then the effect will be similar to strip_defined.

Details

as_character() uses preserve_attributes = TRUE, the resulting vector will retain relevant metadata such as the unit, concept, and namespace attributes, but it will no longer be of class defined. If preserve_attributes = FALSE (default), a plain character vector is returned with all metadata and class dropped.

For numeric-based defined vectors, as_character() will throw an informative error to prevent accidental coercion of non-numeric data.

as.character() will give a warning that as_character() is the preferred method.

Value

A character vector.

See Also

strip_defined()

Examples

as.character(defined(c("a", "b", "c"), label = "Letter code"))
as_character(defined(c("a", "b", "c"), label = "Letter code"))
fruits <- defined(c("apple", "avocado", "kiwi"), label = "Fruit", unit = "kg")
# Keep the metadata, but revert to base R character type:
as_character(fruits, preserve_attributes = TRUE)

# Revert back to base R character type, and do not keep the metadata:
as_character(fruits, preserve_attributes = FALSE)

dataset documentation built on June 8, 2025, 10:15 a.m.