[R] simulate data based on partial correlation matrix
Benjamin Michael Kelcey
bkelcey at umich.edu
Mon Aug 4 22:24:54 CEST 2008
Given four known and fixed vectors, x1,x2,x3,x4, I am trying to
generate a fifth vector,z, with specified known and fixed partial
correlations.
How can I do this?
In the past I have used the following (thanks to Greg Snow) to
generate a fifth vector based on zero order correlations---however I'd
like to modify it so that it can generate a fifth vector with specific
partial correlations rather than zero order correlations:
# create x1-x4
x1 <- rnorm(100, 50, 3)
x2 <- rnorm(100) + x1/5
x3 <- rnorm(100) + x2/5
x4 <- rnorm(100) + x3/5
# find current correlations
cor1 <- cor( cbind(x1,x2,x3,x4) )
cor1
# create 1st version of z
z <- rnorm(100)
# combine in a matrix
m1 <- cbind( x1, x2, x3, x4, z )
# center and scale
m2 <- scale(m1)
# find cholesky decomp
c1 <- chol(var(m2))
# force to be independent
m3 <- m2 %*% solve(c1)
# create new correlation matrix:
cor2 <- cbind( rbind( cor1, z=c(.5,.3,.1,.05) ), z=c(.5,.3,.1,.05,1) )
# create new matrix
m4 <- m3 %*% chol(cor2)
# uncenter and unscale
m5 <- sweep( m4, 2, attr(m2, 'scaled:scale'), '*')
m5 <- sweep( m5, 2, attr(m2, 'scaled:center'), '+')
##Check they are equal
zapsmall(cor(m5))==zapsmall(cor2)
Thanks, ben
More information about the R-help
mailing list