Skip to content

Instantly share code, notes, and snippets.

@certifiedwaif
Created November 21, 2012 04:04
Show Gist options
  • Save certifiedwaif/4122942 to your computer and use it in GitHub Desktop.
Save certifiedwaif/4122942 to your computer and use it in GitHub Desktop.
R code to compute Cronbach's alpha, using the formula interface
cronbach_alpha = function(formula, data=NULL)
{
terms = terms(formula, data=data)
variables = attr(terms, "variables")
var_list = eval(variables, envir=data)
var_mat = t(laply(var_list, identity))
var_mat = var_mat[complete.cases(var_mat),]
response_idx = attr(terms, "response")
response = var_mat[,response_idx]
covariates = var_mat[,-response_idx]
K = dim(covariates)[2]
alpha = K/(K-1) * (1 - sum(diag(var(covariates)))/var(response))
return(alpha)
}
# Example usage
cronbach_alpha(confidence_pa ~ PAtired + PAstress + PAdemands + PAdepress, data=long0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment