Struct RArray

Source
pub struct RArray<T, const NDIM: usize> {
    robj: Robj,
    _data: PhantomData<T>,
}
Expand description

Wrapper for creating and using matrices and arrays.

use extendr_api::prelude::*;
test! {
    let matrix = RMatrix::new_matrix(3, 2, |r, c| [
        [1., 2., 3.],
         [4., 5., 6.]][c][r]);
    let robj = r!(matrix);
    assert_eq!(robj.is_matrix(), true);
    assert_eq!(robj.nrows(), 3);
    assert_eq!(robj.ncols(), 2);

    let matrix2 : RMatrix<f64> = robj.as_matrix().ok_or("error")?;
    assert_eq!(matrix2.data().len(), 6);
    assert_eq!(matrix2.nrows(), 3);
    assert_eq!(matrix2.ncols(), 2);
}

Fields§

§robj: Robj

Owning Robj (probably should be a Pin).

§_data: PhantomData<T>

Data type of the n-array

Implementations§

Source§

impl<T, const NDIM: usize> RArray<T, NDIM>

Source

pub fn get_dimnames(&self) -> List

Source

pub fn get_dim(&self) -> Vec<usize>

Get the dimension vector of the array.

Equivalent to dim() in R

Source

pub fn set_names(&mut self, names: Strings)

Set the names of the elements of an array.

Equivalent to names<- in R

Source

pub fn set_dimnames(&mut self, dimnames: List)

Set the dimension names of an array.

For RMatrix a list of length 2 is required, as that would entail column-names and row-names. If you only wish to set one, but not the other, then the unset element must be R NULL

Equivalent to dimnames<- in R

Source

pub fn set_dim(&mut self, dim: Robj)

Set the dimensions of an array.

Equivalent to dim<-

Source§

impl<T, const NDIM: usize> RArray<T, NDIM>
where T: ToVectorValue, Robj: for<'a> AsTypedSlice<'a, T>,

Source

pub fn new_array(dim: [usize; NDIM]) -> Self

Source§

impl<T> RArray<T, 2>
where T: ToVectorValue, Robj: for<'a> AsTypedSlice<'a, T>,

Source

pub fn new(nrow: usize, ncol: usize) -> Self

Returns an RMatrix with dimensions according to nrow and ncol, with arbitrary entries. To initialize a matrix containing only NA values, use RMatrix::new_with_na.

Source§

impl<T> RArray<T, 2>
where T: ToVectorValue + CanBeNA, Robj: for<'a> AsTypedSlice<'a, T>,

Source

pub fn new_with_na(nrow: usize, ncol: usize) -> Self

Returns an RMatrix with dimensions according to nrow and ncol, with all entries set to NA.

Note that since Raw does not have an NA representation in R, this method is not implemented for [Rbyte].

Source§

impl<T> RArray<T, 2>

Source§

impl<T, const NDIM: usize> RArray<T, NDIM>
where Robj: for<'a> AsTypedSlice<'a, T>,

Source

pub fn from_parts(robj: Robj) -> Self

Source

pub fn data(&self) -> &[T]

Returns a flat representation of the array in col-major.

Source

pub fn data_mut(&mut self) -> &mut [T]

Returns a flat, mutable representation of the array in col-major.

Source

pub fn ndim(&self) -> usize

Returns the number of dimensions.

Source

pub fn dim(&self) -> Vec<usize>

Returns the dimensions of the array.

Source§

impl<T> RArray<T, 1>
where T: ToVectorValue, Robj: for<'a> AsTypedSlice<'a, T>,

Source

pub fn new_column<F: FnMut(usize) -> T>(nrows: usize, f: F) -> Self

Make a new column type.

Source

pub fn nrows(&self) -> usize

Get the number of rows.

Source§

impl<T> RArray<T, 2>
where T: ToVectorValue, Robj: for<'a> AsTypedSlice<'a, T>,

Source

pub fn new_matrix<F: Clone + FnMut(usize, usize) -> T>( nrows: usize, ncols: usize, f: F, ) -> Self

Create a new matrix wrapper.

§Arguments
  • nrows - the number of rows the returned matrix will have
  • ncols - the number of columns the returned matrix will have
  • f - a function that will be called for each entry of the matrix in order to populate it with values. It must return a scalar value that can be converted to an R scalar, such as i32, u32, or f64, i.e. see ToVectorValue. It accepts two arguments:
    • r - the current row of the entry we are creating
    • c - the current column of the entry we are creating
Source

pub fn nrows(&self) -> usize

Get the number of rows.

Source

pub fn ncols(&self) -> usize

Get the number of columns.

Source§

impl<T> RArray<T, 3>
where T: ToVectorValue, Robj: for<'a> AsTypedSlice<'a, T>,

Source

pub fn new_matrix3d<F: Clone + FnMut(usize, usize, usize) -> T>( nrows: usize, ncols: usize, nmatrix: usize, f: F, ) -> Self

Source

pub fn nrows(&self) -> usize

Get the number of rows.

Source

pub fn ncols(&self) -> usize

Get the number of columns.

Source

pub fn nsub(&self) -> usize

Get the number of submatrices.

Methods from Deref<Target = Robj>§

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_integers(&self) -> Option<Integers>

Convert an Robj into Integers.

Source

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

Get a Vec<i32> 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<&[Rbool]>

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

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

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

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

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

pub fn as_logical_iter(&self) -> Option<impl Iterator<Item = &Rbool>>

Get an iterator over logical elements of this slice.

use extendr_api::prelude::*;
test! {
    let robj = r!([TRUE, FALSE, NA_LOGICAL]);
    let mut num_na = 0;
    for val in robj.as_logical_iter().unwrap() {
      if val.is_na() {
          num_na += 1;
      }
    }
    assert_eq!(num_na, 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 Rbool 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<impl Iterator<Item = &f64>>

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<f64> 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_integer_slice_mut(&mut self) -> Option<&mut [i32]>

Get a read-write reference to the content of an integer or logical vector. Note that rust slices are 0-based so slice[1] is the middle value.

use extendr_api::prelude::*;
test! {
    let mut robj = r!([1, 2, 3]);
    let slice : & mut [i32] = robj.as_integer_slice_mut().unwrap();
    slice[1] = 100;
    assert_eq!(robj, r!([1, 100, 3]));
}
Source

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

Get a read-write reference to the content of a double vector. Note that rust slices are 0-based so slice[1] is the middle value.

use extendr_api::prelude::*;
test! {
    let mut robj = r!([1.0, 2.0, 3.0]);
    let slice = robj.as_real_slice_mut().unwrap();
    slice[1] = 100.0;
    assert_eq!(robj, r!([1.0, 100.0, 3.0]));
}
Source

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

Get a read-write reference to the content of a raw vector.

use extendr_api::prelude::*;
test! {
    let mut robj = r!(Raw::from_bytes(&[1, 2, 3]));
    let slice = robj.as_raw_slice_mut().unwrap();
    slice[1] = 100;
    assert_eq!(robj, r!(Raw::from_bytes(&[1, 100, 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<Rbool>

Get a scalar boolean as a tri-boolean Rbool 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().unwrap().is_na(), true);
}

Trait Implementations§

Source§

impl<T: Debug, const NDIM: usize> Debug for RArray<T, NDIM>

Source§

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

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

impl<T, const NDIM: usize> Deref for RArray<T, NDIM>

Source§

type Target = Robj

The resulting type after dereferencing.
Source§

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

Dereferences the value.
Source§

impl<T, const NDIM: usize> DerefMut for RArray<T, NDIM>

Source§

fn deref_mut(&mut self) -> &mut Self::Target

Mutably dereferences the value.
Source§

impl From<&RArray<f64, 2>> for MatRef<'_, f64>

Source§

fn from(value: &RMatrix<f64>) -> Self

Converts to this type from the input type.
Source§

impl<T, const DIM: usize> From<RArray<T, DIM>> for Robj

Source§

fn from(array: RArray<T, DIM>) -> Self

Convert a column, matrix or matrix3d to an Robj.

Source§

impl From<RArray<f64, 2>> for Mat<f64>

Source§

fn from(value: RMatrix<f64>) -> Self

Converts to this type from the input type.
Source§

impl From<RArray<i32, 2>> for Mat<f64>

Source§

fn from(value: RMatrix<i32>) -> Self

Converts to this type from the input type.
Source§

impl<T, const NDIM: usize> Index<[usize; NDIM]> for RArray<T, NDIM>
where Robj: for<'a> AsTypedSlice<'a, T>,

Source§

fn index(&self, index: [usize; NDIM]) -> &Self::Output

Zero-based indexing for DIM-dimensional arrays.

Panics if out of bounds. Zero-based indexing in row, column order.

Panics if out of bounds.

use extendr_api::prelude::*;
test! {
    let matrix = RArray::new_matrix(3, 2, |r, c| [
        [1., 2., 3.],
        [4., 5., 6.]][c][r]);
    assert_eq!(matrix[[0, 0]], 1.);
    assert_eq!(matrix[[1, 0]], 2.);
    assert_eq!(matrix[[2, 1]], 6.);

    let matrix = RArray::new_matrix3d(3, 2, 2, |r, c, d| (r + c + d) as f64);
    assert_eq!(matrix[[0, 0, 0]], 0.);
    assert_eq!(matrix[[1, 0, 1]], 2.);
    assert_eq!(matrix[[2, 1, 1]], 4.);
}
Source§

type Output = T

The returned type after indexing.
Source§

impl<T, const NDIM: usize> IndexMut<[usize; NDIM]> for RArray<T, NDIM>
where Robj: for<'a> AsTypedSlice<'a, T>,

Source§

fn index_mut(&mut self, index: [usize; NDIM]) -> &mut Self::Output

Zero-based mutable indexing for DIM-dimensional arrays.

Panics if out of bounds.

use extendr_api::prelude::*;
test! {
    let mut matrix = RMatrix::new_matrix(3, 2, |_, _| 0.);
    matrix[[0, 0]] = 1.;
    matrix[[1, 0]] = 2.;
    matrix[[2, 0]] = 3.;
    matrix[[0, 1]] = 4.;
    assert_eq!(matrix.as_real_slice().unwrap(), &[1., 2., 3., 4., 0., 0.]);

   let mut matrix = RMatrix3D::new_matrix3d(3, 2, 2, |_, _, _| 0.);
   matrix[[0, 0, 0]] = 1.;
   matrix[[1, 0, 0]] = 2.;
   matrix[[2, 0, 0]] = 3.;
   matrix[[0, 1, 0]] = 4.;
   assert_eq!(matrix.as_real_slice().unwrap(),
       &[1., 2., 3., 4., 0., 0., 0., 0., 0., 0., 0., 0.]);
}
Source§

impl<T, const NDIM: usize> Offset<[usize; NDIM]> for RArray<T, NDIM>

Source§

fn offset(&self, index: [usize; NDIM]) -> usize

Get the offset into the array for a given index.

Source§

impl<T: PartialEq, const NDIM: usize> PartialEq for RArray<T, NDIM>

Source§

fn eq(&self, other: &RArray<T, NDIM>) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · 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<T, const NDIM: usize> StructuralPartialEq for RArray<T, NDIM>

Auto Trait Implementations§

§

impl<T, const NDIM: usize> Freeze for RArray<T, NDIM>

§

impl<T, const NDIM: usize> RefUnwindSafe for RArray<T, NDIM>
where T: RefUnwindSafe,

§

impl<T, const NDIM: usize> !Send for RArray<T, NDIM>

§

impl<T, const NDIM: usize> !Sync for RArray<T, NDIM>

§

impl<T, const NDIM: usize> Unpin for RArray<T, NDIM>
where T: Unpin,

§

impl<T, const NDIM: usize> UnwindSafe for RArray<T, NDIM>
where T: UnwindSafe,

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> 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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

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

§

impl<T> Pointable for T

§

const ALIGN: usize

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
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, 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.