본문 바로가기

Programming/R Script

[R] Correlation Test / Export to Excel File

<R function for correlation test>


1.  cor.test() : to test for association between paired samples (for a single test)


    Using the cor.test(), however, the matrix of p-values can be also made as below.


cor.test.p <- function(x){

    FUN <- function(x, y) cor.test(x, y)[[3]]

    z <- outer(

      colnames(x), 

      colnames(x), 

      Vectorize(function(i,j) FUN(x[,i], x[,j]))

    )

    dimnames(z) <- list(colnames(x), colnames(x))

    z

}

cor.test.p(data)



2. corr.test() :  to find the correlations and reports the sample sizes and probability values as well (for a matrix)


library("psych")

corr.test(data, adjust="none")


The results are not different. Then, let's put the results into an excel file, using an R package, "WriteXLS".


<R function for export of ouput into excel file>


alpha<-0.05

adj<-'bonferroni'

cor.matrix<-NULL

cor.matrix[[1]]<-data.frame(corr.test(data)$r)

cor.matrix[[2]]<-data.frame(corr.test(data)$n)

cor.matrix[[3]]<-data.frame(corr.test(data,adjust="none")$p)

cor.matrix[[4]]<-data.frame(corr.test(data,adjust=adj)$p)

cor.matrix[[5]]<-data.frame(cor.prob.raw<alpha)

cor.matrix[[6]]<-data.frame(cor.prob.adj<alpha)

l<-length(cor.matrix)

for (i in 1:l) {cor.matrix[[i]][lower.tri(cor.matrix[[i]])]<-""}

names(cor.matrix)<-c("cor.matrix","cor.samples","cor.prob.raw",

                     "cor.prob.adj","cor.sig.raw","cor.sig.adj")

library('WriteXLS')

WriteXLS("cor.matrix","CorrelationTest.xls",

         AdjWidth=FALSE, BoldHeaderRow=TRUE, row.names=TRUE)