[R] cor matrix in multivariate regression

Martin Maechler maechler at stat.math.ethz.ch
Tue Oct 22 17:12:43 CEST 2013


>>>>> Suyan Tian <stian at mail.rockefeller.edu>
>>>>>     on Tue, 22 Oct 2013 01:18:10 +0000 writes:

    > Sorry to bother, I want to construct a correlation matrix
    > in multivariate regression (several dependent variables
    > and they are correlated in some ways) like the followings,

    > 1   0.8   0  0 …     0 0 
    > 0.8 1     0  0  …    0 0 
    > 0    0     1  0.8 …  0 0 
    > 0   0      0.8 1  … 0 0 
    > .     .       .     .         ….

    > .     .        .   .          

    > 0  0                      1  0.8 
    > 0  0                       0.8 1 

    > Does anyone know how to do it? 

Of course, with many such problems in R, there are *many* ways.

I believe one of the nicest ways here is to use  toeplitz() :

  n <- 12  ## or whatever your  n is
  toeplitz(c(1,0.8, rep(0, n-2)))

Note that for larger n, under some circumstances it may be
beneficial to use the Matrix package and its *sparse* matrices,
e.g.,

> require(Matrix)
> n <- 12; toeplitz(as(c(1,0.8, rep(0, n-2)), "sparseVector"))
12 x 12 sparse Matrix of class "dsCMatrix"
                                                     
 [1,] 1.0 0.8 .   .   .   .   .   .   .   .   .   .  
 [2,] 0.8 1.0 0.8 .   .   .   .   .   .   .   .   .  
 [3,] .   0.8 1.0 0.8 .   .   .   .   .   .   .   .  
 [4,] .   .   0.8 1.0 0.8 .   .   .   .   .   .   .  
 [5,] .   .   .   0.8 1.0 0.8 .   .   .   .   .   .  
 [6,] .   .   .   .   0.8 1.0 0.8 .   .   .   .   .  
 [7,] .   .   .   .   .   0.8 1.0 0.8 .   .   .   .  
 [8,] .   .   .   .   .   .   0.8 1.0 0.8 .   .   .  
 [9,] .   .   .   .   .   .   .   0.8 1.0 0.8 .   .  
[10,] .   .   .   .   .   .   .   .   0.8 1.0 0.8 .  
[11,] .   .   .   .   .   .   .   .   .   0.8 1.0 0.8
[12,] .   .   .   .   .   .   .   .   .   .   0.8 1.0
> 

Best regards,
Martin Maechler, ETH Zurich



More information about the R-help mailing list