Skip to main content

Function

Struct Function 

Source
pub struct Function { /* private fields */ }
Expand description

Wrapper for creating functions (CLOSSXP).

use extendr_api::prelude::*;
test! {
    let expr = R!("function(a = 1, b) {c <- a + b}").unwrap();
    let func = expr.as_function().unwrap();

    let expected_formals = Pairlist::from_pairs(vec![("a", r!(1.0)), ("b", missing_arg().into())]);
    let expected_body = lang!(
        "{", lang!("<-", sym!(c), lang!("+", sym!(a), sym!(b))));
    assert_eq!(func.formals().as_pairlist().unwrap(), expected_formals);
    assert_eq!(func.body(), expected_body);
    assert_eq!(func.environment(), global_env());
}

Implementations§

Source§

impl Function

Source

pub fn from_parts( formals: Pairlist, body: Language, env: Environment, ) -> Result<Self>

Make a function from parts.

use extendr_api::prelude::*;
test! {
    let formals = pairlist!(a=NULL);
    let body = lang!("+", sym!(a), r!(1)).try_into()?;
    let env = global_env();
    let f = r!(Function::from_parts(formals, body, env )?);
    assert_eq!(f.call(pairlist!(a=1))?, r!(2));
}
Source

pub fn call(&self, args: Pairlist) -> Result<Robj>

Do the equivalent of x(a, b, c)

use extendr_api::prelude::*;
test! {
    let function = R!(function(a, b) a + b).unwrap().as_function().unwrap();
    assert_eq!(function.call(pairlist!(a=1, b=2)).unwrap(), r!(3));
}
Source

pub fn formals(&self) -> Pairlist

Get the formal arguments of the function.

Source

pub fn body(&self) -> Robj

Get the body of the function.

Source

pub fn environment(&self) -> Environment

Get the environment of the function.

Methods from Deref<Target = Robj>§

Source

pub fn as_str_iter(&self) -> Option<StrIter>

Get an iterator over a string vector. Returns None if the object is not a string vector but works for factors.

use extendr_api::prelude::*;

test! {
    let obj = Robj::from(vec!["a", "b", "c"]);
    assert_eq!(obj.as_str_iter().unwrap().collect::<Vec<_>>(), vec!["a", "b", "c"]);

    let factor = factor!(vec!["abcd", "def", "fg", "fg"]);
    assert_eq!(factor.levels().unwrap().collect::<Vec<_>>(), vec!["abcd", "def", "fg"]);
    assert_eq!(factor.as_integer_vector().unwrap(), vec![1, 2, 3, 3]);
    assert_eq!(factor.as_str_iter().unwrap().collect::<Vec<_>>(), vec!["abcd", "def", "fg", "fg"]);
    assert_eq!(factor.as_str_iter().unwrap().collect::<Vec<_>>(), vec!["abcd", "def", "fg", "fg"]);

    let obj = Robj::from(vec![Some("a"), Some("b"), None]);
    assert_eq!(obj.as_str_iter().unwrap().map(|s| s.is_na()).collect::<Vec<_>>(), vec![false, false, true]);

    let obj = Robj::from(vec!["a", "b", na_str()]);
    assert_eq!(obj.as_str_iter().unwrap().map(|s| s.is_na()).collect::<Vec<_>>(), vec![false, false, true]);

    let obj = Robj::from(vec!["a", "b", "NA"]);
    assert_eq!(obj.as_str_iter().unwrap().map(|s| s.is_na()).collect::<Vec<_>>(), vec![false, false, false]);
}
Source

pub fn dollar<T>(&self, symbol: T) -> Result<Robj>
where T: AsRef<str>,

Do the equivalent of x$y

use extendr_api::prelude::*;
test! {
let env = Environment::from_pairs(global_env(),
   vec![("a".to_string(), r!(1)), ("b".to_string(), r!(2))]);
assert_eq!(env.dollar("a").unwrap(), r!(1));
assert_eq!(env.dollar("b").unwrap(), r!(2));
}
Source

pub fn slice<T>(&self, rhs: T) -> Result<Robj>
where T: Into<Robj>,

Do the equivalent of x[y]

use extendr_api::prelude::*;
test! {
let vec = r!([10, 20, 30]);
assert_eq!(vec.slice(2).unwrap(), r!(20));
assert_eq!(vec.slice(2..=3).unwrap(), r!([20, 30]));
}
Source

pub fn index<T>(&self, rhs: T) -> Result<Robj>
where T: Into<Robj>,

Do the equivalent of x[[y]]

use extendr_api::prelude::*;
test! {
let vec = r!([10, 20, 30]);
assert_eq!(vec.index(2).unwrap(), r!(20));
assert_eq!(vec.index(2..=3).is_err(), true);
}
Source

pub fn tilde<T>(&self, rhs: T) -> Result<Robj>
where T: Into<Robj>,

Do the equivalent of x ~ y

use extendr_api::prelude::*;
test! {
    let x = r!(Symbol::from_string("x"));
    let y = r!(Symbol::from_string("y"));
    let tilde = x.tilde(y).unwrap();
    assert_eq!(tilde.inherits("formula"), true);
}
Source

pub fn double_colon<T>(&self, rhs: T) -> Result<Robj>
where T: Into<Robj>,

Do the equivalent of x :: y

use extendr_api::prelude::*;
test! {
let base = r!(Symbol::from_string("base"));
let env = r!(Symbol::from_string(".getNamespace"));
let base_env = base.double_colon(env).unwrap();
assert_eq!(base_env.is_function(), true);
}
Source

pub fn call(&self, args: Pairlist) -> Result<Robj>

Do the equivalent of x(a, b, c)

use extendr_api::prelude::*;
test! {
    let function = R!("function(a, b) a + b").unwrap();
    assert_eq!(function.is_function(), true);
    assert_eq!(function.call(pairlist!(a=1, b=2)).unwrap(), r!(3));
}
Source

pub fn is_null(&self) -> bool

Return true if this is the null object.

Source

pub fn is_symbol(&self) -> bool

Return true if this is a symbol.

Source

pub fn is_logical(&self) -> bool

Return true if this is a boolean (logical) vector

Source

pub fn is_real(&self) -> bool

Return true if this is a real (f64) vector.

Source

pub fn is_complex(&self) -> bool

Return true if this is a complex vector.

Source

pub fn is_expression(&self) -> bool

Return true if this is an expression.

Source

pub fn is_environment(&self) -> bool

Return true if this is an environment.

Source

pub fn is_promise(&self) -> bool

Return true if this is an environment.

Source

pub fn is_string(&self) -> bool

Return true if this is a string.

Source

pub fn is_object(&self) -> bool

Return true if this is an object.

Source

pub fn get_src_filename(&self) -> Robj

Get the source filename.

Source

pub fn as_char(&self) -> Robj

Convert to a string vector.

Source

pub fn coerce_vector(&self, sexptype: u32) -> Robj

Convert to vectors of many kinds.

Source

pub fn pair_to_vector_list(&self) -> Robj

Convert a pairlist (LISTSXP) to a vector list (VECSXP).

Source

pub fn vector_to_pair_list(&self) -> Robj

Convert a vector list (VECSXP) to a pair list (LISTSXP)

Source

pub fn as_character_factor(&self) -> Robj

Convert a factor to a string vector.

Source

pub fn duplicate(&self) -> Self

Do a deep copy of this object. Note that clone() only adds a reference.

Source

pub fn find_function<K: TryInto<Symbol, Error = Error>>( &self, key: K, ) -> Result<Robj>

Find a function in an environment ignoring other variables.

This evaulates promises if they are found.

See also global_function().

use extendr_api::prelude::*;
test! {
   let my_fun = base_env().find_function(sym!(ls)).unwrap();
   assert_eq!(my_fun.is_function(), true);

   // Note: this may crash on some versions of windows which don't support unwinding.
   // assert!(base_env().find_function(sym!(qwertyuiop)).is_none());
}
Source

pub fn find_var<K: TryInto<Symbol, Error = Error>>( &self, key: K, ) -> Result<Robj>

Find a variable in an environment.

See also global_var().

Note that many common variables and functions are contained in promises which must be evaluated and this function may throw an R error.

use extendr_api::prelude::*;
test! {
   let iris_dataframe = global_env()
       .find_var(sym!(iris)).unwrap().eval_promise().unwrap();
   assert_eq!(iris_dataframe.is_frame(), true);
   assert_eq!(iris_dataframe.len(), 5);

   // Note: this may crash on some versions of windows which don't support unwinding.
   //assert_eq!(global_env().find_var(sym!(imnotasymbol)), None);
}
Source

pub fn eval_promise(&self) -> Result<Robj>

If this object is a promise, evaluate it, otherwise return the object.

use extendr_api::prelude::*;
test! {
   let iris_promise = global_env().find_var(sym!(iris)).unwrap();
   let iris_dataframe = iris_promise.eval_promise().unwrap();
   assert_eq!(iris_dataframe.is_frame(), true);
}
Source

pub fn ncols(&self) -> usize

Number of columns of a matrix

Source

pub fn nrows(&self) -> usize

Number of rows of a matrix

Source

pub fn xlengthgets(&self, new_len: usize) -> Result<Robj>

Source

pub fn is_array(&self) -> bool

Return true if this is an array.

Source

pub fn is_factor(&self) -> bool

Return true if this is factor.

Source

pub fn is_frame(&self) -> bool

Return true if this is a data frame.

Source

pub fn is_function(&self) -> bool

Return true if this is a function.

Source

pub fn is_integer(&self) -> bool

Return true if this is an integer vector (INTSXP) but not a factor.

Source

pub fn is_language(&self) -> bool

Return true if this is a language object (LANGSXP).

Source

pub fn is_pairlist(&self) -> bool

Return true if this is NILSXP or LISTSXP.

Source

pub fn is_matrix(&self) -> bool

Return true if this is a matrix.

Source

pub fn is_list(&self) -> bool

Return true if this is NILSXP or VECSXP.

Source

pub fn is_number(&self) -> bool

Return true if this is INTSXP, LGLSXP or REALSXP but not a factor.

Source

pub fn is_primitive(&self) -> bool

Return true if this is a primitive function BUILTINSXP, SPECIALSXP.

Source

pub fn is_ts(&self) -> bool

Return true if this is a time series vector (see tsp).

Source

pub fn is_user_binop(&self) -> bool

Return true if this is a user defined binop.

Source

pub fn is_valid_string(&self) -> bool

Return true if this is a valid string.

Source

pub fn is_valid_string_f(&self) -> bool

Return true if this is a valid string.

Source

pub fn is_vector(&self) -> bool

Return true if this is a vector.

Source

pub fn is_vector_atomic(&self) -> bool

Return true if this is an atomic vector.

Source

pub fn is_vector_list(&self) -> bool

Return true if this is a vector list.

Source

pub fn is_vectorizable(&self) -> bool

Return true if this is can be made into a vector.

Source

pub fn is_raw(&self) -> bool

Return true if this is RAWSXP.

Source

pub fn is_character(&self) -> bool

Return true if this is CHARSXP.

Source

pub fn is_missing_arg(&self) -> bool

Source

pub fn is_unbound_value(&self) -> bool

Source

pub fn is_package_env(&self) -> bool

Source

pub fn package_env_name(&self) -> Robj

Source

pub fn is_namespace_env(&self) -> bool

Source

pub fn namespace_env_spec(&self) -> Robj

Source

pub fn rtype(&self) -> RType

Get the type of an R object.

use extendr_api::prelude::*;
test! {
    assert_eq!(r!(NULL).rtype(), RType::Null);
    assert_eq!(sym!(xyz).rtype(), RType::Symbol);
    assert_eq!(r!(Pairlist::from_pairs(vec![("a", r!(1))])).rtype(), RType::Pairlist);
    assert_eq!(R!("function() {}")?.rtype(), RType::Function);
    assert_eq!(Environment::new_with_parent(global_env()).rtype(), RType::Environment);
    assert_eq!(lang!("+", 1, 2).rtype(), RType::Language);
    assert_eq!(r!(Primitive::from_string("if")).rtype(), RType::Special);
    assert_eq!(r!(Primitive::from_string("+")).rtype(), RType::Builtin);
    assert_eq!(r!(Character::from_string("hello")).rtype(), RType::Character);
    assert_eq!(r!(TRUE).rtype(), RType::Logical);
    assert_eq!(r!(1).rtype(), RType::Integer);
    assert_eq!(r!(1.0).rtype(), RType::Real);
    assert_eq!(r!("1").rtype(), RType::String);
    assert_eq!(r!(List::from_values(&[1, 2])).rtype(), RType::List);
    assert_eq!(parse("x + y")?.rtype(), RType::Expression);
    assert_eq!(r!(Raw::from_bytes(&[1_u8, 2, 3])).rtype(), RType::Raw);
}
Source

pub fn len(&self) -> usize

Get the extended length of the object.

use extendr_api::prelude::*;
test! {

let a : Robj = r!(vec![1., 2., 3., 4.]);
assert_eq!(a.len(), 4);
}
Source

pub fn is_empty(&self) -> bool

Returns true if the Robj contains no elements.

use extendr_api::prelude::*;
test! {

let a : Robj = r!(vec![0.; 0]); // length zero of numeric vector
assert_eq!(a.is_empty(), true);
}
Source

pub fn is_na(&self) -> bool

Is this object is an NA scalar? Works for character, integer and numeric types.

use extendr_api::prelude::*;
test! {

assert_eq!(r!(NA_INTEGER).is_na(), true);
assert_eq!(r!(NA_REAL).is_na(), true);
assert_eq!(r!(NA_STRING).is_na(), true);
}
Source

pub fn as_integer_slice<'a>(&self) -> Option<&'a [i32]>

Get a read-only reference to the content of an integer vector.

use extendr_api::prelude::*;
test! {

let robj = r!([1, 2, 3]);
assert_eq!(robj.as_integer_slice().unwrap(), [1, 2, 3]);
}
Source

pub fn as_integer_iter(&self) -> Option<Int>

Get an iterator over integer elements of this slice.

use extendr_api::prelude::*;
test! {

let robj = r!([1, 2, 3]);
let mut tot = 0;
for val in robj.as_integer_iter().unwrap() {
  tot += val;
}
assert_eq!(tot, 6);
}
Source

pub fn as_integer_vector(&self) -> Option<Vec<i32>>

Get a Vec copied from the object.

use extendr_api::prelude::*;
test! {

let robj = r!([1, 2, 3]);
assert_eq!(robj.as_integer_slice().unwrap(), vec![1, 2, 3]);
}
Source

pub fn as_logical_slice(&self) -> Option<&[Bool]>

Get a read-only reference to the content of a logical vector using the tri-state Bool. Returns None if not a logical vector.

use extendr_api::prelude::*;
test! {
    let robj = r!([TRUE, FALSE, NA_LOGICAL]);
    assert_eq!(robj.as_logical_slice().unwrap(), [TRUE, FALSE, NA_LOGICAL]);
}
Source

pub fn as_logical_vector(&self) -> Option<Vec<Bool>>

Get a Vec copied from the object using the tri-state Bool. Returns None if not a logical vector.

use extendr_api::prelude::*;
test! {
    let robj = r!([TRUE, FALSE, NA_LOGICAL]);
    assert_eq!(robj.as_logical_vector().unwrap(), vec![TRUE, FALSE, NA_LOGICAL]);
}
Source

pub fn as_logical_iter(&self) -> Option<Logical>

Get an iterator over logical elements of this slice.

use extendr_api::prelude::*;
test! {
    let robj = r!([TRUE, FALSE, NA_LOGICAL]);
    let (mut nt, mut nf, mut nna) = (0, 0, 0);
    for val in robj.as_logical_iter().unwrap() {
      match val {
        TRUE => nt += 1,
        FALSE => nf += 1,
        NA_LOGICAL => nna += 1,
        _ => ()
      }
    }
    assert_eq!((nt, nf, nna), (1, 1, 1));
}
Source

pub fn as_real_slice(&self) -> Option<&[f64]>

Get a read-only reference to the content of a double vector. Note: the slice may contain NaN or NA values. We may introduce a “Real” type to handle this like the Bool type.

use extendr_api::prelude::*;
test! {
    let robj = r!([Some(1.), None, Some(3.)]);
    let mut tot = 0.;
    for val in robj.as_real_slice().unwrap() {
      if !val.is_na() {
        tot += val;
      }
    }
    assert_eq!(tot, 4.);
}
Source

pub fn as_real_iter(&self) -> Option<Real>

Get an iterator over real elements of this slice.

use extendr_api::prelude::*;
test! {
    let robj = r!([1., 2., 3.]);
    let mut tot = 0.;
    for val in robj.as_real_iter().unwrap() {
      if !val.is_na() {
        tot += val;
      }
    }
    assert_eq!(tot, 6.);
}
Source

pub fn as_real_vector(&self) -> Option<Vec<f64>>

Get a Vec copied from the object.

use extendr_api::prelude::*;
test! {
    let robj = r!([1., 2., 3.]);
    assert_eq!(robj.as_real_vector().unwrap(), vec![1., 2., 3.]);
}
Source

pub fn as_raw_slice(&self) -> Option<&[u8]>

Get a read-only reference to the content of an integer or logical vector.

use extendr_api::prelude::*;
test! {
    let robj = r!(Raw::from_bytes(&[1, 2, 3]));
    assert_eq!(robj.as_raw_slice().unwrap(), &[1, 2, 3]);
}
Source

pub fn as_string_vector(&self) -> Option<Vec<String>>

Get a vector of owned strings. Owned strings have long lifetimes, but are much slower than references.

use extendr_api::prelude::*;
test! {
   let robj1 = Robj::from("xyz");
   assert_eq!(robj1.as_string_vector(), Some(vec!["xyz".to_string()]));
   let robj2 = Robj::from(1);
   assert_eq!(robj2.as_string_vector(), None);
}
Source

pub fn as_str_vector(&self) -> Option<Vec<&str>>

Get a vector of string references. String references (&str) are faster, but have short lifetimes.

use extendr_api::prelude::*;
test! {
   let robj1 = Robj::from("xyz");
   assert_eq!(robj1.as_str_vector(), Some(vec!["xyz"]));
   let robj2 = Robj::from(1);
   assert_eq!(robj2.as_str_vector(), None);
}
Source

pub fn as_str<'a>(&self) -> Option<&'a str>

Get a read-only reference to a scalar string type.

use extendr_api::prelude::*;
test! {
   let robj1 = Robj::from("xyz");
   let robj2 = Robj::from(1);
   assert_eq!(robj1.as_str(), Some("xyz"));
   assert_eq!(robj2.as_str(), None);
}
Source

pub fn as_integer(&self) -> Option<i32>

Get a scalar integer.

use extendr_api::prelude::*;
test! {
   let robj1 = Robj::from("xyz");
   let robj2 = Robj::from(1);
   let robj3 = Robj::from(NA_INTEGER);
   assert_eq!(robj1.as_integer(), None);
   assert_eq!(robj2.as_integer(), Some(1));
   assert_eq!(robj3.as_integer(), None);
}
Source

pub fn as_real(&self) -> Option<f64>

Get a scalar real.

use extendr_api::prelude::*;
test! {
   let robj1 = Robj::from(1);
   let robj2 = Robj::from(1.);
   let robj3 = Robj::from(NA_REAL);
   assert_eq!(robj1.as_real(), None);
   assert_eq!(robj2.as_real(), Some(1.));
   assert_eq!(robj3.as_real(), None);
}
Source

pub fn as_bool(&self) -> Option<bool>

Get a scalar rust boolean.

use extendr_api::prelude::*;
test! {
   let robj1 = Robj::from(TRUE);
   let robj2 = Robj::from(1.);
   let robj3 = Robj::from(NA_LOGICAL);
   assert_eq!(robj1.as_bool(), Some(true));
   assert_eq!(robj2.as_bool(), None);
   assert_eq!(robj3.as_bool(), None);
}
Source

pub fn as_logical(&self) -> Option<Bool>

Get a scalar boolean as a tri-boolean Bool value.

use extendr_api::prelude::*;
test! {
   let robj1 = Robj::from(TRUE);
   let robj2 = Robj::from([TRUE, FALSE]);
   let robj3 = Robj::from(NA_LOGICAL);
   assert_eq!(robj1.as_logical(), Some(TRUE));
   assert_eq!(robj2.as_logical(), None);
   assert_eq!(robj3.as_logical(), Some(NA_LOGICAL));
}
Source

pub fn eval(&self) -> Result<Robj>

Evaluate the expression in R and return an error or an R object.

use extendr_api::prelude::*;
test! {

   let add = lang!("+", 1, 2);
   assert_eq!(add.eval().unwrap(), r!(3));
}
Source

pub fn eval_with_env(&self, env: &Environment) -> Result<Robj>

Evaluate the expression in R and return an error or an R object.

use extendr_api::prelude::*;
test! {

   let add = lang!("+", 1, 2);
   assert_eq!(add.eval_with_env(&global_env()).unwrap(), r!(3));
}
Source

pub fn eval_blind(&self) -> Robj

Evaluate the expression and return NULL or an R object.

use extendr_api::prelude::*;
test! {
   let bad = lang!("imnotavalidfunctioninR", 1, 2);
   assert_eq!(bad.eval_blind(), r!(NULL));
}
Source

pub fn get_attrib<'a, N>(&self, name: N) -> Option<Robj>
where Self: 'a, Robj: From<N> + 'a,

Get a specific attribute as a borrowed robj if it exists.

use extendr_api::prelude::*;
test! {

   let mut robj = r!("hello");
   robj.set_attrib(sym!(xyz), 1);
   assert_eq!(robj.get_attrib(sym!(xyz)), Some(r!(1)));
}
Source

pub fn set_attrib<N, V>(&self, name: N, value: V) -> Result<Robj>
where N: Into<Robj>, V: Into<Robj>,

Set a specific attribute and return the object.

Note that some combinations of attributes are illegal and this will return an error.

use extendr_api::prelude::*;
test! {

   let mut robj = r!("hello").set_attrib(sym!(xyz), 1)?;
   assert_eq!(robj.get_attrib(sym!(xyz)), Some(r!(1)));
}
Source

pub fn names(&self) -> Option<StrIter>

Get the names attribute as a string iterator if one exists.

use extendr_api::prelude::*;
test! {
   let list = list!(a = 1, b = 2, c = 3);
   let names : Vec<_> = list.names().unwrap().collect();
   assert_eq!(names, vec!["a", "b", "c"]);
}
Source

pub fn set_names<T>(&self, names: T) -> Result<Robj>

Set the names attribute from a string iterator.

Returns Error::NamesLengthMismatch if the length of the names does not match the length of the object.

use extendr_api::prelude::*;
test! {
    let mut obj = r!([1, 2, 3]).set_names(&["a", "b", "c"]).unwrap();
    assert_eq!(obj.names().unwrap().collect::<Vec<_>>(), vec!["a", "b", "c"]);
    assert_eq!(r!([1, 2, 3]).set_names(&["a", "b"]), Err(Error::NamesLengthMismatch(r!(["a", "b"]))));
}
Source

pub fn dim(&self) -> Option<Int>

Get the dim attribute as an integer iterator if one exists.

use extendr_api::prelude::*;
test! {

   let array = R!(array(data = c(1, 2, 3, 4), dim = c(2, 2), dimnames = list(c("x", "y"), c("a","b")))).unwrap();
   let dim : Vec<_> = array.dim().unwrap().collect();
   assert_eq!(dim, vec![2, 2]);
}
Source

pub fn dimnames(&self) -> Option<ListIter>

Get the dimnames attribute as a list iterator if one exists.

use extendr_api::prelude::*;
test! {
   let array = R!(array(data = c(1, 2, 3, 4), dim = c(2, 2), dimnames = list(c("x", "y"), c("a","b")))).unwrap();
   let names : Vec<_> = array.dimnames().unwrap().collect();
   assert_eq!(names, vec![r!(["x", "y"]), r!(["a", "b"])]);
}
Source

pub fn class(&self) -> Option<StrIter>

Get the class attribute as a string iterator if one exists.

use extendr_api::prelude::*;
test! {
   let formula = R!("y ~ A * x + b").unwrap();
   let class : Vec<_> = formula.class().unwrap().collect();
   assert_eq!(class, ["formula"]);
}
Source

pub fn set_class<T>(&self, class: T) -> Result<Robj>

Set the class attribute from a string iterator, returning a new object.

May return an error for some class names.

use extendr_api::prelude::*;
test! {
    let mut obj = r!([1, 2, 3]).set_class(&["a", "b", "c"])?;
    assert_eq!(obj.class().unwrap().collect::<Vec<_>>(), vec!["a", "b", "c"]);
    assert_eq!(obj.inherits("a"), true);
}
Source

pub fn inherits(&self, classname: &str) -> bool

Return true if this class inherits this class.

use extendr_api::prelude::*;
test! {
   let formula = R!("y ~ A * x + b").unwrap();
   assert_eq!(formula.inherits("formula"), true);
}
Source

pub fn levels(&self) -> Option<StrIter>

Get the levels attribute as a string iterator if one exists.

use extendr_api::prelude::*;
test! {
   let factor = factor!(vec!["abcd", "def", "fg", "fg"]);
   let levels : Vec<_> = factor.levels().unwrap().collect();
   assert_eq!(levels, vec!["abcd", "def", "fg"]);
}
Source

pub fn as_column<'a, E: 'a>(&self) -> Option<RColumn<E>>
where Self: AsTypedSlice<'a, E>,

Source

pub fn as_matrix<'a, E: 'a>(&self) -> Option<RMatrix<E>>
where Self: AsTypedSlice<'a, E>,

Source

pub fn as_matrix3d<'a, E: 'a>(&self) -> Option<RMatrix3D<E>>
where Self: AsTypedSlice<'a, E>,

Source

pub fn as_symbol(&self) -> Option<Symbol>

Convert a symbol object to a Symbol wrapper.

use extendr_api::prelude::*;
test! {
    let fred = sym!(fred);
    assert_eq!(fred.as_symbol(), Some(Symbol::from_string("fred")));
}
Source

pub fn as_character(&self) -> Option<Character>

Convert a character object to a Character wrapper.

use extendr_api::prelude::*;
test! {
    let fred = r!(Character::from_string("fred"));
    assert_eq!(fred.as_character(), Some(Character::from_string("fred")));
}
Source

pub fn as_raw(&self) -> Option<Raw>

Convert a raw object to a Character wrapper.

use extendr_api::prelude::*;
test! {
    let bytes = r!(Raw::from_bytes(&[1, 2, 3]));
    assert_eq!(bytes.len(), 3);
    assert_eq!(bytes.as_raw(), Some(Raw::from_bytes(&[1, 2, 3])));
}
Source

pub fn as_language(&self) -> Option<Language>

Convert a language object to a Language wrapper.

use extendr_api::prelude::*;
test! {
    let call_to_xyz = r!(Language::from_values(&[r!(Symbol::from_string("xyz")), r!(1), r!(2)]));
    assert_eq!(call_to_xyz.is_language(), true);
    assert_eq!(call_to_xyz.len(), 3);
    assert_eq!(format!("{:?}", call_to_xyz), r#"r!(Language::from_values([sym!(xyz), r!(1), r!(2)]))"#);
}
Source

pub fn as_pairlist(&self) -> Option<Pairlist>

Convert a pair list object (LISTSXP) to a Pairlist wrapper.

use extendr_api::prelude::*;
test! {
    let names_and_values = vec![("a", r!(1)), ("b", r!(2)), ("", r!(3))];
    let pairlist = Pairlist::from_pairs(names_and_values);
    let robj = r!(pairlist.clone());
    assert_eq!(robj.as_pairlist().unwrap(), pairlist);
}
Source

pub fn as_list(&self) -> Option<List>

Convert a list object (VECSXP) to a List wrapper.

use extendr_api::prelude::*;
test! {
    let list = r!(List::from_values(&[r!(0), r!(1), r!(2)]));
    assert_eq!(list.is_list(), true);
    assert_eq!(format!("{:?}", list), r#"r!(List::from_values([r!(0), r!(1), r!(2)]))"#);
}
Source

pub fn as_expression(&self) -> Option<Expression>

Convert an expression object (EXPRSXP) to a Expr wrapper.

use extendr_api::prelude::*;
test! {
    let expr = r!(Expression::from_values(&[r!(0), r!(1), r!(2)]));
    assert_eq!(expr.is_expression(), true);
    assert_eq!(expr.as_expression(), Some(Expression::from_values(vec![r!(0), r!(1), r!(2)])));
    assert_eq!(format!("{:?}", expr), r#"r!(Expression::from_values([r!(0), r!(1), r!(2)]))"#);
}
Source

pub fn as_environment(&self) -> Option<Environment>

Convert an environment object (ENVSXP) to a Env wrapper.

use extendr_api::prelude::*;
test! {
    let names_and_values = (0..100).map(|i| (format!("n{}", i), i));
    let env = Environment::from_pairs(global_env(), names_and_values);
    let expr = env.clone();
    assert_eq!(expr.len(), 100);
    let env2 = expr.as_environment().unwrap();
    assert_eq!(env2.len(), 100);
}
Source

pub fn as_function(&self) -> Option<Function>

Convert a function object (CLOSXP) to a Function wrapper.

use extendr_api::prelude::*;
test! {
    let func = R!("function(a,b) a + b").unwrap();
    println!("{:?}", func.as_function());
}
Source

pub fn as_promise(&self) -> Option<Promise>

Get a wrapper for a promise.

Trait Implementations§

Source§

impl Clone for Function

Source§

fn clone(&self) -> Function

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Function

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Deref for Function

Source§

fn deref(&self) -> &Self::Target

Make a wrapper behave like an Robj.

Source§

type Target = Robj

The resulting type after dereferencing.
Source§

impl From<Function> for Robj

Source§

fn from(val: Function) -> Self

Make an robj from a wrapper.

Source§

impl<'a> FromRobj<'a> for Function

Source§

fn from_robj(robj: &'a Robj) -> Result<Self, &'static str>

Source§

impl PartialEq for Function

Source§

fn eq(&self, other: &Function) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl TryFrom<Robj> for Function

Source§

fn try_from(robj: Robj) -> Result<Self>

Make a wrapper from a robj if it matches.

Source§

type Error = Error

The type returned in the event of a conversion error.
Source§

impl StructuralPartialEq for Function

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoRobj for T
where Robj: From<T>,

Source§

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.