## R-code for assignment 3 ##################################### ## Part 1 ##################################### ## 2.24 Sigma <- diag(c(4,9,1),3) # a.) solve(Sigma) # b.) eigen(Sigma) # c.) eigen(solve(Sigma)) ## 2.25 Sigma <- matrix(c(25,-2,4,-2,4,1,4,1,9),3,3) # a.) V.sqrt <- sqrt(diag(diag(Sigma),3)) Rho <- solve(V.sqrt)%*%Sigma%*%solve(V.sqrt) # b.) Sigma.test <- V.sqrt%*%Rho%*%V.sqrt ## 3.18 x.bar <- matrix(c(0.766,0.508,0.438,0.161), 4,1) S <- matrix(c(0.856, 0.635, 0.173, 0.096, 0.635, 0.568, 0.127, 0.067, 0.173, 0.128, 0.171, 0.039, 0.096, 0.067, 0.039, 0.043), 4,4) # a.) total <- matrix(c(1,1,1,1),4,1) # sample mean and variance of total x.bar.total <- t(total)%*%x.bar s.sq.total <- t(total)%*%S%*%total x.bar.total s.sq.total # b.) excess <- matrix(c(1,-1,0,0),4,1) # sample mean of t x.bar.excess <- t(excess)%*%x.bar s.sq.excess <- t(excess)%*%S%*%excess x.bar.excess s.sq.excess # covariance between total and excess cov.total.excess <- t(total)%*%S%*%excess cov.total.excess ######################################### ## Part 2 ######################################### glu <- read.table("glucose.txt") summary(glu) ## boxplot boxplot(glu, col="yellow", main="Glucose Measurements", cex.main=1.5) ## density plots par(mfrow=c(3,2)) for(i in 1:6){ plot(density(glu[,i]), lwd=2, main=paste("Glucose", names(glu)[i])) } ## pairs plot par(mfrow=c(1,1)) pairs(glu, pch=16) ## spaghetti plot par(mfrow=c(1,1)) time <- 1:3 plot(time, glu[1,1:3], lwd=2, ylim=c(48,170),type="l", ylab="glucose", xlab="time", cex.lab=1.5, main="Glucose Levels over Time") lines(time, glu[1,4:6], lwd=2, lty=2) for(i in 2:50){ lines(time, glu[i,1:3], lwd=2,type="l", col=i) lines(time, glu[i,4:6], lwd=2, lty=2, col=i) } x.bar <- apply(glu, 2, mean) lines(time, x.bar[1:3], lwd=6, type="l") lines(time, x.bar[4:6], lwd=6, lty=2) ## plot the difference over time for each individual diff <- matrix(0, 50,3) for(i in 1:50){ diff[i,] <- as.numeric(glu[i,1:3] - glu[i,4:6]) } plot(time, diff[1,], lwd=2, ylim=c(-104,15),type="l", ylab="glucose", xlab="time", cex.lab=1.5, main="Difference in Glucose Levels over Time Pre and Post") for(i in 2:50){ lines(time, diff[i,], lwd=2,type="l", col=i) } ########################## sample.mean <- apply(glu, 2, mean) S <- cov(glu) R <- cor(glu) y.bar <- sample.mean[1:3] x.bar <- sample.mean[4:6] sample.mean y.bar x.bar S.yy <- S[1:3, 1:3] S.yx <- S[4:6, 1:3] S.xy <- S[1:3, 4:6] S.xx <- S[4:6, 4:6] S S.yy S.yx S.xy S.xx R.yy <- R[1:3, 1:3] R.yx <- R[4:6, 1:3] R.xy <- R[1:3, 4:6] R.xx <- R[4:6, 4:6] R R.yy R.yx R.xy R.xx