#MULTIVARIATE NORMAL DISTRIBUTION AND CONFIDENCE ELLIPSE: # CREATE DATA USING RANDOM NUMBER GENERATOR: X1=rnorm(1000,0,2) X2=rnorm(1000,0,1) X=cbind(X1,X2) #WRITE DATASET: write.table(X,file="c:/DATA/Multivariate/randombivariate.txt") #============================================================== #START HERE IF YOU WANT TO USE THE SAME DATA MATRIX: #READ DATASET FROM FILE: M=read.table("c:/DATA/Multivariate/randombivariate.txt") plot(M,asp=1,cex=0.5,pch=19,col='blue') #CALCULATE MEAN AND STANDARD DEVIATION OF REALIZED DATA: summary(M) sd(M) #CONFIDENCE ELLIPSE: library(latticeExtra) attach(M) xyplot(X2 ~ X1, scales = "free",aspect='iso', par.settings = list(plot.symbol = list(col='blue',cex = 0.5, pch=19)), panel = function(x, y, ...) { panel.xyplot(x, y, ...) panel.ellipse(x,y,lwd = 1,level=0.68,col='green', ...) panel.ellipse(x,y,lwd = 1,level=0.90,col='brown', ...) panel.ellipse(x,y,lwd = 2,level=0.95,col='red', ...) }, auto.key = list(x = .1, y = .8, corner = c(0, 0))) #============================================================== #APPLYING CORRELATION BETWEEN VARIABLES IN MATRIX M #USING LINEAR TRANSFORMATION: A=matrix(c(1,1.5,1.5,1),nrow=2,ncol=2,byrow=TRUE) A Mnew1=t(A%*%as.matrix(t(M))) cor(Mnew1) #CONFIDENCE ELLIPSE: library(latticeExtra) detach(M) xyplot(Mnew1[,2] ~ Mnew1[,1], scales = "free",aspect='iso', par.settings = list(plot.symbol = list(col='blue',cex = 0.5, pch=19)), panel = function(x, y, ...) { panel.xyplot(x, y, ...) panel.ellipse(x,y,lwd = 1,level=0.68,col='green', ...) panel.ellipse(x,y,lwd = 1,level=0.90,col='brown', ...) panel.ellipse(x,y,lwd = 2,level=0.95,col='red', ...) }, auto.key = list(x = .1, y = .8, corner = c(0, 0))) #============================================================== #USING A DIFFERENT LINEAR TRANSFORMATION: A=matrix(c(1,-0.25,-0.25,1),nrow=2,ncol=2,byrow=TRUE) A Mnew2=t(A%*%as.matrix(t(M))) cor(Mnew2) #CONFIDENCE ELLIPSE: library(latticeExtra) xyplot(Mnew2[,2] ~ Mnew2[,1], scales = "free",aspect='iso', par.settings = list(plot.symbol = list(col='blue',cex = 0.5, pch=19)), panel = function(x, y, ...) { panel.xyplot(x, y, ...) panel.ellipse(x,y,lwd = 1,level=0.68,col='green', ...) panel.ellipse(x,y,lwd = 1,level=0.90,col='brown', ...) panel.ellipse(x,y,lwd = 2,level=0.95,col='red', ...) }, auto.key = list(x = .1, y = .8, corner = c(0, 0)))