[R] Creating a correlation matrix with significance levels

fxen3k f.sehardt at gmail.com
Fri Oct 12 13:17:00 CEST 2012


Hi there,

I tried this code from homepage: 
http://myowelt.blogspot.de/2008/04/beautiful-correlation-tables-in-r.html
<http://myowelt.blogspot.de/2008/04/beautiful-correlation-tables-in-r.html>  

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)
} 

Output_cor <- xtable(corstarsl(swiss[,1:4]))
setwd(paste(path,"Output/Correlation/",sep=""))
print.xtable(Output_cor, type="html", file="correlation.html")

In this example it shows the output of package example Hmisc. I want to use
this code for my own matrix  called:

Corr_Matrix <- cbind(MA_data_raw$1, MA_data_raw$2, MA_data_raw$3,
MA_data_raw$4, MA_data_raw$5, MA_data_raw$6, MA_data_raw$7, MA_data_raw$8,
I(MA_data_raw$21/MA_data_raw$20), MA_data_raw$9)

How can I do this? 

Thanks! 
I appreciate all helpful answers! ;-)



--
View this message in context: http://r.789695.n4.nabble.com/Creating-a-correlation-matrix-with-significance-levels-tp4645984.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list