Alex
Alex

Reputation: 353

Creating matrix in R, is there a faster way?

So basically, here is the matrix I need to create

sig = matrix(c(0.56^2, 0.56*7.77*-0.07, 0.56*13.48*-0.095, 0.56*16.64*-0.095,
               0.56*7.77*-0.07, 7.77^2, 7.77*13.48*0.959, 7.77*16.64*0.936,
               0.56*13.48*-0.095, 7.77*13.48*0.959, 13.48^2, 13.48*16.64*0.997,
               0.56*16.64*-0.095, 7.77*16.64*0.936, 13.48*16.64*0.997, 16.64^2), nrow = 4, ncol = 4)

I am writing to ask if there is some better way to figure out the matrix without actually entering every value? It is very easy to make mistakes, I suppose.

Upvotes: 0

Views: 94

Answers (1)

G. Grothendieck
G. Grothendieck

Reputation: 269644

This looks like a covariance matrix so define the standard deviations, d, and define the correlations (in the upper triangular portion of the correlation matrix), cors, and reconstruct sig from those two.

Given d and cors we define m to be a diagonal matrix with 1/2 in each diagonal element. Then in the next line insert the correlations into its upper triangular part. In the following line we fill in the lower triangular part by adding t(m) which also sets the diagonal elements to 1 (1/2 + 1/2 = 1) giving the correlation matrix corr. Finally convert corr to a covariance matrix by multiplying by outer.

d <- c(0.56, 7.77, 13.48, 16.64)
cors <- c(-0.07, -0.095, 0.959, -0.095, 0.936, 0.997)

m <- diag(length(d))/2
m[upper.tri(m)] <- cors
corr <- m + t(m)
sig2 <- corr * outer(d, d)

all.equal(sig, sig2)
## [1] TRUE

Other direction

Note that to go in the other direction, i.e. derive d and cors from sig, that the standard deviations and correlations are respectively:

d2 <- sqrt(diag(sig))
all.equal(d, d2)
## [1] TRUE

cors2 <- cov2cor(sig)[upper.tri(sig)]
all.equal(cors, cors2)
## [1] TRUE

Upvotes: 5

Related Questions