Wednesday, June 6, 2012

Correlation Tables in R flagged with significance level stars (*, **, and ***)

If you want to create a lower triangle correlation matrix  which is flagged with stars (*, **, and ***) according to levels of statistical significance, this syntax may be helpful (found it here). All you have to do is cut and paste into R and insert your data table. You will need the Hmisc and xtable packages.

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

##Create table _insert your dataframe below
New_table<-corstarsl(yourdataframe)




## exporting tables to either html or .tex (I prefer .tex but you will have to install TeX)

print.xtable(newtable, type="latex", file="filename.tex")
print.xtable(newtable, type="html", file="filename.html") ## see here for formatting tips

4 comments:

  1. This is super helpful! Thanks for sharing. :)

    ReplyDelete
  2. The best correlation function i have ever used,very useful and time-saving, many thanks !

    ReplyDelete
  3. New_table<-corstarsl(yourdataframe)
    When I run this line I get this type of erroe...
    Error in as.matrix(x) : object 'yourdataframe' not found
    How can I fix this error

    ReplyDelete
  4. also find this error...
    > print.xtable(newtable, type="latex", file="filename.tex")
    Error in print.xtable(newtable, type = "latex", file = "filename.tex") :
    object 'newtable' not found

    ReplyDelete