-
Notifications
You must be signed in to change notification settings - Fork 1
/
cholcorr.R
44 lines (35 loc) · 1.12 KB
/
cholcorr.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
cholcorr<-function(cmatrix, obs=1000, seed=5, printit=TRUE,...){
#Determine if Seed needs to be Set
if(seed)
set.seed(seed)
##Determin Length of Correlation Martix
row=nrow(cmatrix)
col=ncol(cmatrix)
if (row==col) {
#Cholesky Decomposition of C Matrix
U=chol(cmatrix)
#Uncorrelated Normally Distributed Random variables
R=matrix(rnorm(obs*col), nrow=obs)
#Matrix of Correlated Variables
M=R %*% U
#Store as a data frame
output=data.frame(M)
rdata=data.frame(R)
#Show Correlations of the now correlated variables
if(printit){
cat("Observed Correlation\n\n")
cat("Seed: ",seed,"\n")
cat("Number of observations: ", obs, "\n\n")
output.print = cor(output)
output.print = apply(output.print, 2, format, digits=4, nsmall=TRUE)
print(as.data.frame(output.print))
}
#Store as list
invisible(list(cordata=output, randata=rdata, obscor=cor(output), obs=obs, seed=seed))
}
else {
#the reason why I put "stop" here is because you want users to know that it is an error to not
#use an n X n matrix.
stop("Correlation Matrix must be of dimensions n X n")
}
}