Last active
December 16, 2020 02:17
-
-
Save anhqle/5855936 to your computer and use it in GitHub Desktop.
R code to create pretty correlation table (+ Latex output)
Source: somewhere on the Internet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(xtable) | |
corstarsl <- function(x){ | |
require(Hmisc) | |
x <- as.matrix(x) | |
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]) | |
return(Rnew) | |
} | |
corstarsl(swiss[,1:4]) | |
xtable(corstarsl(swiss[,1:4])) #Latex code |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The source is probably this site: http://myowelt.blogspot.de/2008/04/beautiful-correlation-tables-in-r.html