You are on page 1of 3

## Law example for rho:

law=data.frame(matrix(c(1 , 576 , 3.39 ,


2 , 635 , 3.30,
3 , 558 , 2.81,
4 , 579 , 3.03,
5 , 666 , 3.44,
6 , 580 , 3.07,
7 , 555 , 3.00,
8 , 661 , 3.43,
9 , 651 , 3.36,
10 , 605 , 3.13,
11 , 653 , 3.12,
12 , 575 , 2.74,
13 , 545 , 2.76,
14 , 572 , 2.88,
15 , 594 , 2.96),ncol=3,byrow=T))
dimnames(law)[[2]]=c("School","LSAT","GPA")
attach(law)
plot(LSAT,GPA,pch=16)
cor(LSAT,GPA)
get.1.bootstrapped.r=function(n=15,data=law){
## Get indices of resampled observations:
chosen=sample(1:n,replace=T)
## Get new bootstrap sample:
bootstrap.sample=law[chosen,]
## Calculate r:
r=cor(bootstrap.sample$LSAT,bootstrap.sample$GPA)
return(r)
}
r.bootstrap=get.1.bootstrapped.r(15,law)
B=1000
bootstrapped.r.values=rep(0,B)
for (i in 1:B){bootstrapped.r.values[i]=get.1.bootstrapped.r(15,law)}
hist(bootstrapped.r.values,col="grey80",n=16)
abline(v=0.7766,col="red",lwd=2)
box()
legend(.3,150,"Observed r",lty=1,lwd=2,col="red")
## Get a 90% CI for rho:
quantile(bootstrapped.r.values,0.05)
quantile(bootstrapped.r.values,0.95)
hist(bootstrapped.r.values,col="grey80",n=16)
box()
abline(v=0.5374,lwd=3)
abline(v=0.9507,lwd=3)
arrows(.3,46,.425,20,lwd=2)
text(.3,65,"5% lower tail")
text(.3,55,"or 50 observations")
arrows(.975,77,.975,50,lwd=2)
text(.985,105,"5%")
text(.990,95,"upper")
text(.985,85,"tail")

###############
library(boot)
get.r=function(data,indices){
## order rows of data by 'indices':
data=data[indices,]
## Calculate r:
r=cor(data$LSAT,data$GPA)
return(r)
}
boot.out=boot(law,get.r,R=1000)
boot.ci(boot.out,conf=0.90,type="perc")
###############
library(car)
attach(Anscombe)
head(Anscombe)
plot(income,education)
lm.out=lm(education ~ income)
par(mfrow=c(1,2))
plot(lm.out$fitted.values,lm.out$residuals,pch=16)
abline(h=0)
qqnorm(lm.out$residuals,pch=16)
qqline(lm.out$residuals)
get.coeffic=function(data,indices){
data=data[indices,]
lm.out=lm(education ~ income,data=data)
return(lm.out$coefficients)
}
n=nrow(Anscombe)
get.coeffic(Anscombe,1:n)

boot.out=boot(Anscombe,get.coeffic,R=1000)
boot.out$t
boot.ci(boot.out,index=2,conf=0.95,type="perc")
boot.ci(boot.out,index=1,type="perc",conf=0.95)
plot(c(-.01,0.09),c(-100,125),type="n",xlab="slope",
ylab="intercept")
points(boot.out$t[,2],boot.out$t[,1],col=2)
dataEllipse(boot.out$t[,2],boot.out$t[,1],levels=c(.5,.95,.99),add=TRUE,plo
t.points=FALSE,col=1)
abline(h=0,lwd=2)
abline(v=0,lwd=2)
apply(boot.out$t,2,mean)

You might also like