[R] display only the top-right half of a correlation matrix?

Liviu Andronic landronimirc at gmail.com
Fri Aug 19 22:45:08 CEST 2011


On Fri, Aug 19, 2011 at 9:38 PM, Peter Langfelder
<peter.langfelder at gmail.com> wrote:
> if as.dist doesn't work, use brute force:
>
> x = matrix(rnorm(5*100), 100, 5)
> mat = signif(cor(x), 2);
> mat[lower.tri(mat)] = ""
>
> data.frame(mat)
>
Yes, brute force works. This isn't quite how I wanted to do this, but
the following seems to work for me.

Thanks all
Liviu

require(Hmisc)
print.rcorr <-
    function (x, upper=FALSE, ...)
{
    r <- format(round(x$r, 2))
    if(!is.null(upper)) r[if(!upper) upper.tri(r) else lower.tri(r)] <- ''
    print(data.frame(r))
    n <- x$n
    if (all(n == n[1, 1]))
        cat("\nn=", n[1, 1], "\n\n")
    else {
        cat("\nn\n")
        print(n)
    }
    cat("\nP\n")
    P <- x$P
    P <- ifelse(P < 0.0001, 0, P)
    p <- format(round(P, 4))
    p[is.na(P)] <- ""
    if(!is.null(upper)) p[if(!upper) upper.tri(p) else lower.tri(p)] <- ''
    print(p, quote = FALSE)
    invisible()
}

> (xb <- rcorr(as.matrix(mtcars[ , 1:4])))
       mpg   cyl  disp    hp
mpg   1.00
cyl  -0.85  1.00
disp -0.85  0.90  1.00
hp   -0.78  0.83  0.79  1.00

n= 32


P
     mpg cyl disp hp
mpg
cyl   0
disp  0   0
hp    0   0   0



More information about the R-help mailing list