Skip to content

Instantly share code, notes, and snippets.

@hdbt
Last active November 13, 2023 10:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hdbt/49c045646320d95fd6e7d6a50067c7be to your computer and use it in GitHub Desktop.
Save hdbt/49c045646320d95fd6e7d6a50067c7be to your computer and use it in GitHub Desktop.
Correlation Matrix
corstarsl <- function(xx){
require(Hmisc)
x <- as.matrix(xx)
R <- rcorr(x)$r
p <- rcorr(x)$P
## define notions for significance levels; spacing is important.
mystars <- ifelse(p < .001, "***", ifelse(p < .01, "** ", ifelse(p < .05, "* ", " ")))
## trunctuate the matrix that holds the correlations to two decimal
R <- format(round(cbind(rep(-1.11, ncol(x)), R), 2))[,-1]
## build a new matrix that includes the correlations with their apropriate stars
Rnew <- matrix(paste(R, mystars, sep=""), ncol=ncol(x))
diag(Rnew) <- paste(diag(R), " ", sep="")
rownames(Rnew) <- colnames(x)
colnames(Rnew) <- paste(colnames(x), "", sep="")
## remove upper triangle
Rnew <- as.matrix(Rnew)
Rnew[upper.tri(Rnew, diag = TRUE)] <- ""
Rnew <- as.data.frame(Rnew)
## remove last column and return the matrix (which is now a data frame)
Rnew <- cbind(Rnew[1:length(Rnew)-1])
## add summary columns
not.na = function(x, ...) sum(!is.na(x))
stats <- xx %>%
summarise_all(c("mean","sd", "not.na"),na.rm = TRUE) %>%
unlist() %>%
matrix(ncol = 3 ) %>%
as.tibble() %>%
rename( "Mean" = V1, "SD" = V2, "N" = V3)
Rnew <- cbind(Rnew, stats)
return(Rnew)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment