[R] simulate data from multivariate normal with pre-specified correlation matrix

Jiao Yang yj316 at gwu.edu
Mon Aug 13 23:15:12 CEST 2007


For example, the correlation matrix is 3x3 and looks like 

1       0.75  0  0  0
0.75    1     0  0  0
 0       0     0   0  0

Can I write the code like  this?

p<- 3 # number of variables per observation
N<- 10 # number of samples

# define population correlation matrix sigma
sigma<-matrix(0,p,p) #creates a px p matrix of 0
rank<-2
for (i in 1:rank){
for (j in 1:rank){
rho<-0.75
 sigma[i,j]<-rho^abs(i-j)
sigma[i,i]<-1
 }
}

# create a data set of 10 observations from multivariate normalcovariance matrix sigma  
library(MASS)
Xprime<-mvrnorm(N,rep(1,p), sigma )

Also, if I calculate

S<- cov(Xprime) 

will S be the sample correlation matrix?

Thank you very much for your time!



More information about the R-help mailing list