Skip to content

Instantly share code, notes, and snippets.

@jailop
Created March 15, 2025 22:30
Show Gist options
  • Select an option

  • Save jailop/84563bd7a7e1d22897274ae9af40fb4e to your computer and use it in GitHub Desktop.

Select an option

Save jailop/84563bd7a7e1d22897274ae9af40fb4e to your computer and use it in GitHub Desktop.
Cronbach's Alpha Calculation
/**
* In a survey questionnaire, a set of items can be included
* referred to the same construct or concept. Therefore,
* it is expected that responses for those items are similar
* or highly correlated. To measure that, the Cronbach’s
* Alpha is frequently used. It estimates the reliability
* or the internal consistency for a set of survey items.
*/
/**
* Computes the variance of a items contained in a vector.
*
* \sigma^2 = \frac{\sum(x_i - \bar{x})^2}{n - 1}
*/
fn variance(data: &Vec<f64>) -> f64 {
let n = data.len() as f64;
let mean = data.iter().sum::<f64>() / n;
let sqr_diff: f64 = data.iter()
.map(|x| (x - mean).powi(2)).sum();
sqr_diff / (n - 1.0)
}
/**
* Computes the Cronbach's Alpha.
* It measures the reliability for a set of item surveys.
* \alpha = \frac{n}{n - 1} (1 - \frac{\sum \sigma_i^2}{\sigma_T^2})
*/
fn cronbach_alpha(data: &Vec<Vec<f64>>) -> f64 {
let n = data[0].len() as f64;
// item variances
let mut var_items = Vec::new();
for j in 0..n as usize {
let col: Vec<f64> = data.iter()
.map(|row| row[j]).collect();
var_items.push(variance(&col));
}
// total score variances
let total_scores: Vec<f64> = data.iter()
.map(|row| row.iter().sum()).collect();
let var_total = variance(&total_scores);
// cronbach's alpha
let sum_var_items: f64 = var_items.iter().sum();
(n / (n - 1.0)) *
(1.0 - (sum_var_items / var_total))
}
fn main() {
// rows are respondents
// columns are responses to the survey items
let responses = vec![
vec![4.0, 4.0, 4.0, 5.0],
vec![3.0, 4.0, 3.0, 4.0],
vec![5.0, 4.0, 5.0, 5.0],
vec![2.0, 3.0, 2.0, 3.0],
vec![4.0, 4.0, 4.0, 4.0],
];
let alpha = cronbach_alpha(&responses);
println!("Cronbach's Alpha: {:.4}", alpha);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment