Skip to main content

Module factor

Module factor 

Source
Expand description

Factor support for enum ↔ R factor conversions.

Provides the RFactor trait for converting Rust enums to/from R factors. Use #[derive(RFactor)] on C-style enums to auto-generate the implementation.

§Example

ⓘ
use miniextendr_api::RFactor;

#[derive(Copy, Clone, RFactor)]
enum Color { Red, Green, Blue }

#[miniextendr]
fn color_name(c: Color) -> &'static str {
    match c {
        Color::Red => "red",
        Color::Green => "green",
        Color::Blue => "blue",
    }
}

Factor support for enum ↔ R factor conversions.

R factors are integer vectors with a levels attribute (character vector) and a class attribute set to "factor". The integer payload uses 1-based indexing into the levels, with NA_INTEGER for missing values.

§Usage

ⓘ
use miniextendr_api::RFactor;

#[derive(Copy, Clone, RFactor)]
enum Color { Red, Green, Blue }

// Enum values convert to/from R factors automatically
#[miniextendr]
fn describe(c: Color) -> &'static str {
    match c {
        Color::Red => "red",
        Color::Green => "green",
        Color::Blue => "blue",
    }
}

Structs§

Factor
A borrowed view into an R factor’s integer indices.
FactorMut
A mutable borrowed view into an R factor’s integer indices.
FactorOptionVec
Wrapper for Vec<Option<T: RFactor>> with NA support.
FactorVec
Wrapper for Vec<T: UnitEnumFactor> enabling IntoR/TryFromSexp.

Statics§

FACTOR_CLASS 🔒

Traits§

RFactor
Trait for mapping Rust enums to R factors.
UnitEnumFactor
Trait implemented by unit-only enums derived via #[derive(DataFrameRow)].

Functions§

build_factor
Build a factor SEXP from indices and a levels STRSXP.
build_factor_with_levels
Build a factor SEXP from indices and level names in a single call.
build_levels_sexp
Build a levels STRSXP of UTF-8 CHARSXPs.
build_levels_sexp_cached
Build a levels STRSXP and preserve it permanently (for caching).
build_levels_sexp_protected 🔒
Keep the container rooted while each level’s CHARSXP is allocated.
code_not_a_level 🔒
The reason a factor code does not name one of the levels (a malformed factor: validate_factor_levels has already checked the level set).
factor_class_sexp 🔒
factor_from_sexp
Convert an R factor SEXP to a single enum value.
factor_option_vec_from_sexp 🔒
Convert an R factor SEXP to a Vec of Option enum values (NA → None).
factor_vec_from_sexp 🔒
Convert an R factor SEXP to a Vec of enum values. Every NA and every code outside the levels is reported, with its position.
read_factor_codes 🔒
Read every code of a factor through elt, batching every failing element (its reason and 1-based position) into one error instead of stopping at the first.
unit_factor_option_vec_from_sexp
Convert an R factor SEXP to a Vec<Option<T>> using UnitEnumFactor (NA → None).
validate_factor_levels 🔒
Validate that a factor has the expected levels.