#Homework 3 - Problem Number 1# #This code modifies newrt to count the number of rejections # # required before it actually produces the random number. # # It then counts the number of times required for each of # # 2, 8, and 30 degrees of freedom. It produces summary # # statistics for the number of rejections and then produces # # a q-q plot for each of these. It is not surprising that # # the normality assumption for either the t-test or ANOVA is # # not met. One nonparametric test that could be used instead # # of a one-way ANOVA is the Kruskal-Wallis test. # # The inside front cover of Conover's nonparametric book has # # a nice list of when different tests should be used. # newrt<-function(df=1){ #generates a t random variable using the accept-reject method# check<-0 nrejects<--1 while (check==0){ nrejects<-nrejects+1 y1<-runif(1)*2-1 y2<-runif(1) if (y2<0.5){x<-y1} else {x<-1/y1} u<-runif(1) if (u<= (((1+(x^2)/df)^(-(df+1)/2) )/min(1,x^(-2)))) {check<-1} } return(x,nrejects) } rejects2<-rep(0,500) rejects8<-rep(0,500) rejects30<-rep(0,500) for (i in 1:500){ rejects2[i]<-newrt(df=2)$nrejects rejects8[i]<-newrt(df=8)$nrejects rejects30[i]<-newrt(df=30)$nrejects } par(mfrow=c(3,1)) summary(rejects2) summary(rejects8) summary(rejects30) qqnorm(rejects2) qqnorm(rejects8) qqnorm(rejects30) kruskal.test(c(rejects2,rejects8,rejects30),c(rep(2,500),rep(8,500),rep(30,500))) #Homework 3 - Problem Number 2# #This code modifies mvrnorm to generate multivariate random # # variables using the correlation matrix and variance vector # # instead of the covariance matrix. It then tries a brief # # example to make sure it works. # library(MASS) mvrnorm2<-function(n,mu,vars,corr){ #put some comments here# sigma<-corr*(sqrt(vars)%*%t(sqrt(vars))) mvrnorm(n,mu,sigma)} mu<-c(5,84,13) vars<-c(18,1,4) corr<-matrix(c(1,.4,.7,.4,1,.9,.7,.9,1),nrow=3) x<-mvrnorm2(5000,mu,vars,corr) apply(x,2,mean) var(x) cor(x)