as_logical: Coerce a defined vector to logical

View source: R/as_logical.R

as_logicalR Documentation

Coerce a defined vector to logical

Description

Coerces a haven_labelled_defined vector created with defined() into a base R logical vector.

This function is the recommended, semantic-aware interface for converting defined logical vectors. It preserves the underlying logical values and, unless otherwise requested, retains the semantic metadata attached to the variable.

Usage

as_logical(x, ...)

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

Arguments

x

A vector created with defined().

...

Additional arguments (currently unused).

strip_attributes

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

Details

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

Users may also call base R's as.logical(), which will dispatch to this method automatically via S3. However, as_logical() is preferred because it makes the semantics explicit and supports the strip_attributes argument.

Value

A logical vector. If strip_attributes = FALSE, any semantic metadata attached to x will be carried over to the returned vector.

See Also

as_numeric(), as_character(), as.Date(), as.POSIXct(), defined()

Examples

# Basic usage
flg <- defined(c(TRUE, FALSE, TRUE), label = "Flag")
as_logical(flg)

# Metadata preserved by default
attr(as_logical(flg), "label")

# Stripping metadata
as_logical(flg, strip_attributes = TRUE)

# Base R coercion also works (via S3 method dispatch)
as.logical(flg)


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