Skip to content

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

6 messages · Peter Langfelder, Jean V Adams, Liviu Andronic

#
Dear all
Is there an easy way to display only one half (top-right or
bottom-left) of a correlation matrix?
mpg   cyl  disp    hp
mpg   1.00 -0.85 -0.85 -0.78
cyl  -0.85  1.00  0.90  0.83
disp -0.85  0.90  1.00  0.79
hp   -0.78  0.83  0.79  1.00

n= 32


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


Since the two sides are identical, there is little value in having
both displayed at the same time. Moreover, it considerably slows down
the inspection of the results.

Thank you
Liviu
#
On Fri, Aug 19, 2011 at 11:50 AM, Liviu Andronic <landronimirc at gmail.com> wrote:
Use as.dist: here's an example.
1             2             3             4
2 -2.892981e-06
3  2.873711e-02  1.002969e-02
4 -5.803705e-02  4.022733e-02 -6.154211e-02
5  1.137083e-01 -8.065676e-02 -9.279316e-02 -8.201583e-02
#
On Fri, Aug 19, 2011 at 9:02 PM, Peter Langfelder
<peter.langfelder at gmail.com> wrote:
Seems promising, but for one issue: I would like to keep the diagonal
and thus specify 'diag=T', but then as.dist() replaces the diagonal
values with zero. (See below.) Is there a way to prevent it from doing
that? Either keep the original values, or not display anything in the
diagonal (as for the upper part)?

Regards
Liviu
mpg   cyl  disp    hp
mpg   1.00 -0.85 -0.85 -0.78
cyl  -0.85  1.00  0.90  0.83
disp -0.85  0.90  1.00  0.79
hp   -0.78  0.83  0.79  1.00

n= 32


P
     mpg cyl disp hp
mpg       0   0    0
cyl   0       0    0
disp  0   0        0
hp    0   0   0
mpg   cyl  disp    hp
mpg   0.00
cyl  -0.85  0.00
disp -0.85  0.90  0.00
hp   -0.78  0.83  0.79  0.00
#
On Fri, Aug 19, 2011 at 12:32 PM, Liviu Andronic <landronimirc 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)

Peter
#
On Fri, Aug 19, 2011 at 9:38 PM, Peter Langfelder
<peter.langfelder at gmail.com> wrote:
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()
}
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