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

From: Olivier ETERRADOSSI <olivier.eterradossi_at_ema.fr>
Date: Thu 05 Apr 2007 - 09:09:01 GMT


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@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@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@intermountainmail.org]
> Sent: Wednesday, April 04, 2007 1:46 AM
> To: Nguyen Dinh Nguyen; r-help@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

______________________________________________
R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
Received on Thu Apr 05 19:15:38 2007

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Thu 05 Apr 2007 - 15:30:47 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.