[R] cor.test in matrices

Frank E Harrell Jr fharrell at virginia.edu
Wed Mar 5 23:14:17 CET 2003


On Wed, 05 Mar 2003 22:34:16 +0100
"juli g. pausas" <juli at ceam.es> wrote:

> Hi,
> For computing correlation among variables in a matrix, I use cor( ), but 
> for computing the p-values I'm using cor.test in the following way:
> 
> cor.p <- function(X)
> {
> res <- matrix(0, ncol(X), ncol(X))
> for (i in 1:ncol(X))
> for (j in 1:ncol(X)) res[i, j]<- cor.test(X[, i], X[, j])$p.value
> rownames(res) <- colnames(res) <- colnames(X)
> res
> }
> 
> I'm just wondering if there is a better (nicer) way to do the same.
> For example, would it be possible to use apply() with cor.test instead 
> of using the for loops?
> I'm trying to improve my low R skills.
> Thanks
> 
> Juli
>

One approach is to install the Hmisc package and run rcorr(X) which will give you a matrix of P values for Pearson or Spearman correlations.  See http://hesweb1.med.virginia.edu/biostat/s/Hmisc.html

-- 
Frank E Harrell Jr              Prof. of Biostatistics & Statistics
Div. of Biostatistics & Epidem. Dept. of Health Evaluation Sciences
U. Virginia School of Medicine  http://hesweb1.med.virginia.edu/biostat



More information about the R-help mailing list