Constructing correlated variables

浪子不回头ぞ 提交于 2019-12-01 11:00:21

I did something similar a while ago. I am pasting some code that is for 3 correlated variables but it can be easily generalized to something more complex.

Create an F matrix first:

cor_Matrix <-  matrix(c (1.00, 0.90, 0.20 ,
                     0.90, 1.00, 0.40 ,
                     0.20, 0.40, 1.00), 
                  nrow=3,ncol=3,byrow=TRUE)

This can be an arbitrary correlation matrix.

library(psych) 

fit<-principal(cor_Matrix, nfactors=3, rotate="none")

fit$loadings

loadings<-matrix(fit$loadings[1:3, 1:3],nrow=3,ncol=3,byrow=F)
loadings

#create three rannor variable

cases <- t(replicate(3, rnorm(3000)) ) #edited, changed to 3000 cases from 150 cases

multivar <- loadings %*% cases
T_multivar <- t(multivar)

var<-as.data.frame(T_multivar)

cor(var)

Again, this can be generalized. You approach listed above does not create a multivariate data set.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!