as_numeric()
is the recommended method to convert a defined()
vector to a numeric vector. It ensures the underlying data is numeric and can
optionally preserve semantic metadata.
Base R's as.numeric()
does not support custom classes like defined()
.
This method drops all metadata and class information, returning a plain
numeric vector. It is equivalent to as_numeric(x, preserve_attributes = FALSE)
.
Usage
as_numeric(x, ...)
# S3 method for class 'haven_labelled_defined'
as_numeric(x, preserve_attributes = FALSE, ...)
# S3 method for class 'haven_labelled_defined'
as.numeric(x, ...)
Arguments
- x
A vector created with
defined()
.- ...
Reserved for future use.
- preserve_attributes
Logical. Whether to keep metadata attributes. Defaults to
FALSE
.
Value
A numeric vector (either bare or with metadata, depending on the
preserve_attributes
argument).
Details
If preserve_attributes = TRUE
, the returned vector retains the unit
,
concept
, and namespace
attributes, but is no longer of class "defined"
.
If FALSE
(default), a base numeric vector is returned without metadata.
For character-based defined
vectors, an error is thrown to avoid invalid
coercion.
Examples
gdp <- defined(c(3897L, 7365L), label = "GDP", unit = "million dollars")
# Drop all metadata
as_numeric(gdp)
#> [1] 3897 7365
# Preserve unit and concept
as_numeric(gdp, preserve_attributes = TRUE)
#> [1] 3897 7365
#> attr(,"label")
#> [1] "GDP"
#> attr(,"unit")
#> [1] "million dollars"
# Equivalence to base coercion (without metadata)
as.numeric(gdp)
#> [1] 3897 7365
# Metadata-aware variant preferred in pipelines
attr(as_numeric(gdp, TRUE), "unit")
#> [1] "million dollars"