Skip to main content

Module as_coerce

Module as_coerce 

Source
Expand description

Traits for R’s as.<class>() coercion functions.

This module provides traits for implementing R’s generic coercion methods (as.data.frame(), as.list(), as.character(), etc.) for Rust types wrapped in ExternalPtr.

See the as_coerce module documentation for usage examples. Traits for R’s as.<class>() coercion functions.

This module provides traits that enable Rust types wrapped in ExternalPtr<T> to define how they convert to R base types. When used with the #[miniextendr(as = "...")] attribute, these generate proper S3 method wrappers for R’s coercion generics.

§Supported Conversions

R GenericRust TraitMethod
as.data.frameAsDataFrameas_data_frame(&self)
as.listAsListas_list(&self)
as.characterAsCharacteras_character(&self)
as.numeric / as.doubleAsNumericas_numeric(&self)
as.integerAsIntegeras_integer(&self)
as.logicalAsLogicalas_logical(&self)
as.matrixAsMatrixas_matrix(&self)
as.vectorAsVectoras_vector(&self)
as.factorAsFactoras_factor(&self)
as.DateAsDateas_date(&self)
as.POSIXctAsPOSIXctas_posixct(&self)
as.complexAsComplexas_complex(&self)
as.rawAsRawas_raw(&self)
as.environmentAsEnvironmentas_environment(&self)
as.functionAsFunctionas_function(&self)

§Usage with #[miniextendr]

Use #[miniextendr(as = "...")] on impl methods to generate S3 method wrappers:

use miniextendr_api::{miniextendr, ExternalPtr, List};
use miniextendr_api::as_coerce::AsCoerceError;

pub struct MyData {
    names: Vec<String>,
    values: Vec<f64>,
}

#[miniextendr(s3)]
impl MyData {
    pub fn new(names: Vec<String>, values: Vec<f64>) -> Self {
        Self { names, values }
    }

    /// Convert to data.frame
    #[miniextendr(as = "data.frame")]
    pub fn as_data_frame(&self) -> Result<List, AsCoerceError> {
        if self.names.len() != self.values.len() {
            return Err(AsCoerceError::InvalidData {
                message: "names and values must have same length".into(),
            });
        }
        Ok(List::from_pairs(vec![
            ("name", self.names.clone()),
            ("value", self.values.clone()),
        ])
        .set_class_str(&["data.frame"])
        .set_row_names_int(self.names.len()))
    }

    /// Convert to character representation
    #[miniextendr(as = "character")]
    pub fn as_character(&self) -> Result<String, AsCoerceError> {
        Ok(format!("MyData({} items)", self.values.len()))
    }
}

This generates R S3 methods:

# Generated automatically:
as.data.frame.MyData <- function(x, ...) {
    .Call(C_MyData__as_data_frame, .call = match.call(), x)
}

as.character.MyData <- function(x, ...) {
    .Call(C_MyData__as_character, .call = match.call(), x)
}

Enums§

AsCoerceError
Error type for as.<class>() coercion failures.

Constants§

SUPPORTED_AS_GENERICS
All supported R coercion generics.

Traits§

AsCharacter
Trait for types that can be coerced to character via as.character().
AsComplex
Trait for types that can be coerced to complex via as.complex().
AsDataFrame
Trait for types that can be coerced to data.frame via as.data.frame().
AsDate
Trait for types that can be coerced to Date via as.Date().
AsEnvironment
Trait for types that can be coerced to environment via as.environment().
AsFactor
Trait for types that can be coerced to factor via as.factor().
AsFunction
Trait for types that can be coerced to function via as.function().
AsInteger
Trait for types that can be coerced to integer via as.integer().
AsList
Trait for types that can be coerced to list via as.list().
AsLogical
Trait for types that can be coerced to logical via as.logical().
AsMatrix
Trait for types that can be coerced to matrix via as.matrix().
AsNumeric
Trait for types that can be coerced to numeric/double via as.numeric().
AsPOSIXct
Trait for types that can be coerced to POSIXct via as.POSIXct().
AsRaw
Trait for types that can be coerced to raw via as.raw().
AsVector
Trait for types that can be coerced to a generic vector via as.vector().

Functions§

is_supported_as_generic
Check if a generic name is a supported as.<class>() generic.
r_generic_to_method
Maps an R generic name to the corresponding trait method name.