public
Last active

Annotated version of myboot

  • Download Gist
myboot.R
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
myboot<-function(data, stat, nreps, hist = TRUE) {
# Where 'data' is the original data set to be paste into 'myboot' program.
# 'stat' is the function that will generate the desired statistic such as "standard errors", "confidence intervals" etc.
# 'nreps' is the number of repetitions we want in the simulation.
estimates<-get(stat)(data)# Compute the number of estimates needed:
len<-length(estimates)
# Make a container object matrix for store the bootstrap results:
container<-matrix(NA, ncol = len , nrow = nreps)
# The length of "estimates" is the number of coefficients we will estimate standard errors for.
nobs<-nrow(data)#Compute the number of observations to resample
for(i in 1:nreps) {
# Now let's start our bootstrapping resampling loop
posdraws<-ceiling(runif(nobs)*nobs)
# Draw nobs uniform integers draws from 1 to nobs
resample<-data[posdraws,]
# This will sample a random sample from the original data
container[i,]<-get(stat)(resample)
# This apply the function 'stat' to the new data table and store it as a row in 'container' object
}
### 1.2 ### This will compute standard deviation for each column
sds<-apply(container,2,sd)
if(hist==T) {
mfrow=c(1,1)
frame() # alias for plot.new()
if(len<= 3) par(mfrow=c(len,1))
if((len> 3)&(len<= 6)) par(mfrow=c(3,2))
for(j in 1:len) hist(container[,j],
main=paste("Estimates for ", names(estimates)[j]), xlab="")
}
print(rbind(estimates,sds))
return(list(estimation=container, sds=sds))
}
 
###@ 2 @###
mod<-function(griliches76){
model<-lm(lw~s+iq, data=griliches76)
coef<-model[[1]]
# This function generates a vector with the boostrap estimates.
#mod1<-function(griliches76)lm(lw~s+iq, data=griliches76)[[1]]
}
mod1.res<-myboot(griliches76, "mod", 10000, hist=T)
# This will run the bootstrap function on the estimates 10.000 times and plot a histogram for the found distribution.

Here's a remix of your code. The resampling is done with sample, and the function will show a progress bar. I have used the foreach package to make the computation parallelizable.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.