[R] 3D correlation

Martin Elff elff at sowi.uni-mannheim.de
Wed Feb 6 10:53:38 CET 2008


On Wednesday 06 February 2008 (01:35:15), ramakg at cecs.pdx.edu wrote:
> how to generate correlated data which is correlated in three variables??

# Your correlation matrix
S <- rbind(
  c(1,.3,.3),
  c(.3,1,.3),
  c(.3,.3,1)
  )

# Three independent normal variates
x1 <- rnorm(1000)
x2 <- rnorm(1000)
x3 <- rnorm(1000)

# Using the cholesky decomposition of S
Y <- cbind(x1,x2,x3)%*%chol(S)

# Three correlated normal variates
y1 <- Y[,1]
y2 <- Y[,2]
y3 <- Y[,3]

# Check
cor(Y)

There may be more elegant and general solutions and
you can also use package "mvtnorm" to get correlated
normal (or t) variates. But the principle comes down
to this.

Hope that helps,

Martin



More information about the R-help mailing list