Skip to content
Prev 200477 / 398502 Next

simulated correlated vectors

Try this:

x <- rexp(100, 1/3)

xp <- scale(x)

cor.mat <- rbind( c(1, 0.8, 0.7), c(0.8, 1, 0.3), c(0.7, 0.3, 1) )

x23 <- matrix( rnorm( 100 * 2, 1/3 ), ncol=2 )

x23 <- cbind(xp, scale(x23)) 

x23 <- x23 %*% solve(chol(var(x23))) ## skip if you don't want exact cor's

x.new <- x23 %*% chol(cor.mat) 
x.new[,1] <- x.new[,1]*attr(xp, 'scaled:scale') + attr(xp, 'scaled:center')

all.equal( x.new[,1], x )

cor(x.new)
pairs(x.new)


you can generate the data from other distributions than the normal, and you can add and multiply constants in the columns of x.new to give different means/sd's.  This will set the correlations, but the exact distributions of the columns is not guaranteed.

Hope this helps,