I am trying to generate random data (using R programming) for variables e1,e2,e3 which should have zero correlation with random variable R. Variables e should have zero correlation with each other. The code written for generating variable e with zero correlation with R as follows:
R <- rnorm(120,mean=8,sd=16)
n <- 120 # length of vectors e
rho <- 0 # desired correlation = cos(angle)
nrSamples = 3 # since we have three vectors to estimate (e1,e2,e3)
Id <- diag(n)
theta<- acos(rho) # corresponding angle
e <- list(mode="vector",length=nrSamples)
x <- list(mode="vector",length=nrSamples)
X <- list(mode="vector",length=nrSamples)
Xctr <- list(mode="vector",length=nrSamples)
Q <- list(mode="vector",length=nrSamples)
P <- list(mode="vector",length=nrSamples)
x2o <- list(mode="vector",length=nrSamples)
Xc2 <- list(mode="vector",length=nrSamples)
Y <- list(mode="vector",length=nrSamples)
for (i in 1:nrSamples) {
x[[i]] <- rnorm(n, 0, 2)
X[[i]] <- cbind(R, x[[i]]) # matrix
Xctr[[i]] <- scale(X[[i]], center=TRUE, scale=FALSE) # centered columns(mean 0)
Q[[i]] <- qr.Q(qr(Xctr[[i]][ , 1, drop=FALSE]))
P[[i]] <- tcrossprod(Q[[i]]) # = Q Q' # projection onto space defined by x1
x2o[[i]] <- (Id-P[[i]]) %*% Xctr[[i]][ , 2] # x2ctr made orthogonal to x1ctr
Xc2[[i]] <- cbind(Xctr[[i]][ , 1], x2o[[i]]) # bind to matrix
Y [[i]] <- Xc2[[i]] %*% diag(1/sqrt(colSums(Xc2[[i]]^2)))
e[[i]] <- Y[[i]][ , 2] + (1 / tan(theta)) * Y[[i]][ , 1]
} vector_1 <- e[[1]]
vector_2 <- e[[2]]
vector_3 <- e[[3]]
Aucun commentaire:
Enregistrer un commentaire