[R] Generate a serie of new vars that correlate with existingvar

Olivier ETERRADOSSI olivier.eterradossi at ema.fr
Thu Apr 5 11:09:01 CEST 2007


Hello, list
why not add the smart proposal by Greg Snow as a built-in function in 
{stats},
just changing the "x234" and "newc" lines to allow for more 
distributions to be generated ?
Or do I miss an already existing function to do that ?
Regards. Olivier


# slight modification of the original code by Greg Snow 
[mailto:Greg.Snow at intermountainmail.org]
# on April 04, 2007 1:46 AM

# generates ndistr vectors of same mean and sd, with various cor.coeffs
# input :
#         x1 : a vector
#         ndistr : number of distributions
#         coefs : vector o ndistr correl. coeffs

CorelSets<-function(x1= rnorm(100, 15, 5),ndistr=3, coefs=c(0.4,0.5,0.6)){

# x2, x3, and x4 in a matrix, these will be modified to meet the criteria
x234 <- scale(matrix( rnorm(ndistr*length(x1)), ncol=ndistr ))

# put all into 1 matrix for simplicity
x1234 <- cbind(scale(x1),x234)

# find the current correlation matrix
c1 <- var(x1234)

# cholesky decomposition to get independence
chol1 <- solve(chol(c1))

newx <-  x1234 %*% chol1

# check that we have independence and x1 unchanged
zapsmall(cor(newx))
all.equal( x1234[,1], newx[,1] )

# create new correlation structure
newc<-diag(ndistr+1)
newc[1,-1]<- coefs
newc[-1,1]<- coefs

chol2 <- chol(newc)

finalx <- newx %*% chol2 * sd(x1) + mean(x1)
pairs(finalx)
CorelSets<-finalx
}
> Message-ID: <000c01c77642$a9555750$0fe05e81 at D145LD1S>
> Content-Type: text/plain;	charset="us-ascii"
>
> Dear Greg,
> Thanks million!
> "As good as it gets"  :) 
> All the best
> Nguyen
>
> -----Original Message-----
> From: Greg Snow [mailto:Greg.Snow at intermountainmail.org] 
> Sent: Wednesday, April 04, 2007 1:46 AM
> To: Nguyen Dinh Nguyen; r-help at stat.math.ethz.ch
> Subject: RE: [R] Generate a serie of new vars that correlate with existing
> var
>
> Here is one way to do it:......8<.................snip.........8<....
>   
-- 
Olivier ETERRADOSSI
Maître-Assistant
CMGD / Equipe "Propriétés Psycho-Sensorielles des Matériaux"
Ecole des Mines d'Alès
Hélioparc, 2 av. P. Angot, F-64053 PAU CEDEX 9
tel std: +33 (0)5.59.30.54.25
tel direct: +33 (0)5.59.30.90.35 
fax: +33 (0)5.59.30.63.68
http://www.ema.fr



More information about the R-help mailing list