Skip to main content

Module r_coerce

Module r_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 r_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.

§Tradeoff

These traits are about exposing user-controlled conversions to R callers via S3 method dispatch — they’re not the inbound/outbound conversion path for #[miniextendr] arguments and return values. For that, see crate::from_r::TryFromSexp / crate::into_r::IntoR (and crate::coerce::Coerce / crate::strict for the lax/strict pairs). Failure mode of confusing the two: an RCoerceList impl will not satisfy a fn foo(_: MyType) argument coming from R — that needs TryFromSexp.

§Supported Conversions

R GenericRust TraitMethod
as.data.frameRCoerceDataFrameas_data_frame(&self)
as.listRCoerceListas_list(&self)
as.characterRCoerceCharacteras_character(&self)
as.numeric / as.doubleRCoerceNumericas_numeric(&self)
as.integerRCoerceIntegeras_integer(&self)
as.logicalRCoerceLogicalas_logical(&self)
as.matrixRCoerceMatrixas_matrix(&self)
as.vectorRCoerceVectoras_vector(&self)
as.factorRCoerceFactoras_factor(&self)
as.DateRCoerceDateas_date(&self)
as.POSIXctRCoercePOSIXctas_posixct(&self)
as.complexRCoerceComplexas_complex(&self)
as.rawRCoerceRawas_raw(&self)
as.environmentRCoerceEnvironmentas_environment(&self)
as.functionRCoerceFunctionas_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::r_coerce::RCoerceError;

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, RCoerceError> {
        if self.names.len() != self.values.len() {
            return Err(RCoerceError::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, RCoerceError> {
        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§

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

Constants§

SUPPORTED_AS_GENERICS
All supported R coercion generics.

Traits§

RCoerceCharacter
Trait for types that can be coerced to character via as.character().
RCoerceComplex
Trait for types that can be coerced to complex via as.complex().
RCoerceDataFrame
Trait for types that can be coerced to data.frame via as.data.frame().
RCoerceDate
Trait for types that can be coerced to Date via as.Date().
RCoerceEnvironment
Trait for types that can be coerced to environment via as.environment().
RCoerceFactor
Trait for types that can be coerced to factor via as.factor().
RCoerceFunction
Trait for types that can be coerced to function via as.function().
RCoerceInteger
Trait for types that can be coerced to integer via as.integer().
RCoerceList
Trait for types that can be coerced to list via as.list().
RCoerceLogical
Trait for types that can be coerced to logical via as.logical().
RCoerceMatrix
Trait for types that can be coerced to matrix via as.matrix().
RCoerceNumeric
Trait for types that can be coerced to numeric/double via as.numeric().
RCoercePOSIXct
Trait for types that can be coerced to POSIXct via as.POSIXct().
RCoerceRaw
Trait for types that can be coerced to raw via as.raw().
RCoerceVector
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.