as_numeric: Coerce a defined vector to numeric

View source: R/defined.R

as.numeric.haven_labelled_definedR Documentation

Coerce a defined vector to numeric

Description

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

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

Usage

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

as_numeric(x, ...)

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

Arguments

x

A vector created with defined.

...

Further arguments passed to internal methods (not used).

preserve_attributes

Defaults to FALSE, in which case the unit, concept and namespace attributes will be preserved, but the returned value will otherwise become a base R integer, double or numeric value. If false, then the effect will be similar to strip_defined.

Details

as_numeric() allows preserve_attributes = TRUE when 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 numeric vector is returned with all metadata and class dropped.
For character-based defined vectors, as_numeric() will throw an informative error to prevent accidental coercion of non-numeric data.

Value

A numeric vector.

See Also

as_numeric

strip_defined()

Examples

as_numeric(orange_df$age, preserve_attributes = TRUE)
gdp <- defined(c(3897L, 7365L), label = "GDP", unit = "million dollars")
gdp_numbers <- as_numeric(gdp)
gdp_numbers
attributes(gdp_numbers)

gdp_striped <- as_numeric(gdp, preserve_attributes = FALSE)
attributes(gdp_striped)

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