kmo <- function(x) { x <- subset(x, complete.cases(x)) # Omit missing values r <- cor(x) # Correlation matrix r2 <- r^2 # Squared correlation coefficients i <- solve(r) # Inverse matrix of correlation matrix d <- diag(i) # Diagonal elements of inverse matrix p2 <- (-i/sqrt(outer(d, d)))^2 # Squared partial correlation coefficients diag(r2) <- diag(p2) <- 0 # Delete diagonal elements KMO <- sum(r2)/(sum(r2)+sum(p2)) MSA <- colSums(r2)/(colSums(r2)+colSums(p2)) return(list(KMO=KMO, MSA=MSA)) }