r2rs-stats 0.1.1

Statistics programming for Rust based on R's stats package
Documentation
use nalgebra::DMatrix;

// TODO: Should these be weighted?

pub fn regression_sum_of_squares(x: &DMatrix<f64>, y: &DMatrix<f64>, b: &DMatrix<f64>) -> f64 {
    let n = x.shape().0;
    (b.transpose() * x.transpose() * y)[(0, 0)] - (y.sum().powi(2) / n as f64)
}

pub fn residual_sum_of_squares(x: &DMatrix<f64>, y: &DMatrix<f64>, b: &DMatrix<f64>) -> f64 {
    ((y.transpose() * y) - (b.transpose() * x.transpose() * y))[(0, 0)].abs()
}

pub fn weighted_residual_sum_of_squares(
    x: &DMatrix<f64>,
    y: &DMatrix<f64>,
    b: &DMatrix<f64>,
    w: &DMatrix<f64>,
) -> f64 {
    let mut residuals = y - (x * b);
    residuals
        .iter_mut()
        .zip(w.iter())
        .for_each(|(resid, weight)| *resid = resid.abs() * weight);
    residuals.sum()
}

pub fn total_sum_of_squares(x: &DMatrix<f64>, y: &DMatrix<f64>) -> f64 {
    let n = x.shape().0;
    (y.transpose() * y)[(0, 0)] - (y.sum() / n as f64)
}