SlightlyBuilt
SlightlyBuilt

Reputation: 147

r easy nxn covariance matrix creation with given variances and covariances

For a simulation study I need to create nxn covariance matrices. for example I can input 2x2 covariance matrices like

     [,1] [,2]
[1,] 1.0  1.5
[2,] 1.5  2.0

into a r function/object:

var <- c(1,2) ## variances
covar <- c(1.5,1.5) ## covariance(s)
mat <- matrix(c(var[1],covar[1],covar[2],var[2]),ncol=length(var))

then I only have to change var & covar values to form the matrices. but unfortunately I'm not just dealing with 2x2s but 2x2:30x30 or even higher! so is it possible to write only one function for any matrix of nxn dimension in r?

Upvotes: 2

Views: 554

Answers (1)

Colonel Beauvel
Colonel Beauvel

Reputation: 31161

You can do:

m <- diag(variance)
m[lower.tri(m)] = m[upper.tri(m)] <- head(covar, length(covar)/2)

For example:

variance = c(0.25, 0.75, 0.6)
covar = c(0.1, 0.3, 0.2, 0.1, 0.3, 0.2)

#>m
#     [,1] [,2] [,3]
#[1,] 0.25 0.10  0.3
#[2,] 0.10 0.75  0.2
#[3,] 0.30 0.20  0.6

Upvotes: 2

Related Questions